blob: 880c840fd4ceee82b5b77b255d38da7936844d51 [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.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000293///
294Action::OwningExprResult
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)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000300 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000301
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();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000313
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 // Get an array type for the string, according to C99 6.4.5. This includes
315 // the nul terminator character as well as the string length for pascal
316 // strings.
317 StrTy = Context.getConstantArrayType(StrTy,
318 llvm::APInt(32, Literal.GetStringLength()+1),
319 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000320
Chris Lattner4b009652007-07-25 00:24:17 +0000321 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sebastian Redlcd883f72009-01-18 18:53:16 +0000322 return Owned(new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
323 Literal.AnyWide, StrTy,
324 StringToks[0].getLocation(),
325 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000326}
327
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000328/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
329/// CurBlock to VD should cause it to be snapshotted (as we do for auto
330/// variables defined outside the block) or false if this is not needed (e.g.
331/// for values inside the block or for globals).
332///
333/// FIXME: This will create BlockDeclRefExprs for global variables,
334/// function references, etc which is suboptimal :) and breaks
335/// things like "integer constant expression" tests.
336static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
337 ValueDecl *VD) {
338 // If the value is defined inside the block, we couldn't snapshot it even if
339 // we wanted to.
340 if (CurBlock->TheDecl == VD->getDeclContext())
341 return false;
342
343 // If this is an enum constant or function, it is constant, don't snapshot.
344 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
345 return false;
346
347 // If this is a reference to an extern, static, or global variable, no need to
348 // snapshot it.
349 // FIXME: What about 'const' variables in C++?
350 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
351 return Var->hasLocalStorage();
352
353 return true;
354}
355
356
357
Steve Naroff0acc9c92007-09-15 18:49:24 +0000358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000359/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000360/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000362/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364 IdentifierInfo &II,
365 bool HasTrailingLParen,
366 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000367 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
368}
369
Douglas Gregor566782a2009-01-06 05:10:23 +0000370/// BuildDeclRefExpr - Build either a DeclRefExpr or a
371/// QualifiedDeclRefExpr based on whether or not SS is a
372/// nested-name-specifier.
373DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
374 bool TypeDependent, bool ValueDependent,
375 const CXXScopeSpec *SS) {
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
Sebastian Redlcd883f72009-01-18 18:53:16 +0000412Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000413Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
414 FieldDecl *Field,
415 Expr *BaseObjectExpr,
416 SourceLocation OpLoc) {
417 assert(Field->getDeclContext()->isRecord() &&
418 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
419 && "Field must be stored inside an anonymous struct or union");
420
421 // Construct the sequence of field member references
422 // we'll have to perform to get to the field in the anonymous
423 // union/struct. The list of members is built from the field
424 // outward, so traverse it backwards to go from an object in
425 // the current context to the field we found.
426 llvm::SmallVector<FieldDecl *, 4> AnonFields;
427 AnonFields.push_back(Field);
428 VarDecl *BaseObject = 0;
429 DeclContext *Ctx = Field->getDeclContext();
430 do {
431 RecordDecl *Record = cast<RecordDecl>(Ctx);
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 {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000487 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
488 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000489 }
490 ExtraQuals = MD->getTypeQualifiers();
491 }
492
493 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000494 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
495 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000496 }
497
498 // Build the implicit member references to the field of the
499 // anonymous struct/union.
500 Expr *Result = BaseObjectExpr;
501 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
502 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
503 FI != FIEnd; ++FI) {
504 QualType MemberType = (*FI)->getType();
505 if (!(*FI)->isMutable()) {
506 unsigned combinedQualifiers
507 = MemberType.getCVRQualifiers() | ExtraQuals;
508 MemberType = MemberType.getQualifiedType(combinedQualifiers);
509 }
510 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
511 OpLoc, MemberType);
512 BaseObjectIsPointer = false;
513 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
514 OpLoc = SourceLocation();
515 }
516
Sebastian Redlcd883f72009-01-18 18:53:16 +0000517 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000518}
519
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000520/// ActOnDeclarationNameExpr - The parser has read some kind of name
521/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
522/// performs lookup on that name and returns an expression that refers
523/// to that name. This routine isn't directly called from the parser,
524/// because the parser doesn't know about DeclarationName. Rather,
525/// this routine is called by ActOnIdentifierExpr,
526/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
527/// which form the DeclarationName from the corresponding syntactic
528/// forms.
529///
530/// HasTrailingLParen indicates whether this identifier is used in a
531/// function call context. LookupCtx is only used for a C++
532/// qualified-id (foo::bar) to indicate the class or namespace that
533/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000534///
535/// If ForceResolution is true, then we will attempt to resolve the
536/// name even if it looks like a dependent name. This option is off by
537/// default.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000538Sema::OwningExprResult
539Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
540 DeclarationName Name, bool HasTrailingLParen,
541 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregora133e262008-12-06 00:22:45 +0000542 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
543 HasTrailingLParen && !SS && !ForceResolution) {
544 // We've seen something of the form
545 // identifier(
546 // and we are in a template, so it is likely that 's' is a
547 // dependent name. However, we won't know until we've parsed all
548 // of the call arguments. So, build a CXXDependentNameExpr node
549 // to represent this name. Then, if it turns out that none of the
550 // arguments are type-dependent, we'll force the resolution of the
551 // dependent name at that point.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000552 return Owned(new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
553 Context.DependentTy, Loc));
Douglas Gregora133e262008-12-06 00:22:45 +0000554 }
555
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000556 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000557 Decl *D = 0;
558 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000559 if (SS && !SS->isEmpty()) {
560 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
561 if (DC == 0)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000562 return ExprError();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000563 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000564 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000565 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
566
Sebastian Redlcd883f72009-01-18 18:53:16 +0000567 if (Lookup.isAmbiguous()) {
568 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
569 SS && SS->isSet() ? SS->getRange()
570 : SourceRange());
571 return ExprError();
572 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000573 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000574
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000575 // If this reference is in an Objective-C method, then ivar lookup happens as
576 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000577 IdentifierInfo *II = Name.getAsIdentifierInfo();
578 if (II && getCurMethodDecl()) {
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");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000591 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
592 ObjCIvarRefExpr *MRef = new ObjCIvarRefExpr(IV, IV->getType(), Loc,
593 static_cast<Expr*>(SelfExpr.release()),
594 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000595 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000596 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000597 }
598 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000599 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000600 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000601 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000602 getCurMethodDecl()->getClassInterface()));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000603 return Owned(new ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000604 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000605 }
Chris Lattner4b009652007-07-25 00:24:17 +0000606 if (D == 0) {
607 // Otherwise, this could be an implicitly declared function reference (legal
608 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000609 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000610 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000611 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000612 else {
613 // If this name wasn't predeclared and if this is not a function call,
614 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000615 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
617 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
619 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 return ExprError(Diag(Loc, diag::err_undeclared_use)
621 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000622 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
625 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000626
627 // We may have found a field within an anonymous union or struct
628 // (C++ [class.union]).
629 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
630 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
631 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000632
Douglas Gregor3257fb52008-12-22 05:46:06 +0000633 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
634 if (!MD->isStatic()) {
635 // C++ [class.mfct.nonstatic]p2:
636 // [...] if name lookup (3.4.1) resolves the name in the
637 // id-expression to a nonstatic nontype member of class X or of
638 // a base class of X, the id-expression is transformed into a
639 // class member access expression (5.2.5) using (*this) (9.3.2)
640 // as the postfix-expression to the left of the '.' operator.
641 DeclContext *Ctx = 0;
642 QualType MemberType;
643 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
644 Ctx = FD->getDeclContext();
645 MemberType = FD->getType();
646
647 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
648 MemberType = RefType->getPointeeType();
649 else if (!FD->isMutable()) {
650 unsigned combinedQualifiers
651 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
652 MemberType = MemberType.getQualifiedType(combinedQualifiers);
653 }
654 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
655 if (!Method->isStatic()) {
656 Ctx = Method->getParent();
657 MemberType = Method->getType();
658 }
659 } else if (OverloadedFunctionDecl *Ovl
660 = dyn_cast<OverloadedFunctionDecl>(D)) {
661 for (OverloadedFunctionDecl::function_iterator
662 Func = Ovl->function_begin(),
663 FuncEnd = Ovl->function_end();
664 Func != FuncEnd; ++Func) {
665 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
666 if (!DMethod->isStatic()) {
667 Ctx = Ovl->getDeclContext();
668 MemberType = Context.OverloadTy;
669 break;
670 }
671 }
672 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000673
674 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000675 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
676 QualType ThisType = Context.getTagDeclType(MD->getParent());
677 if ((Context.getCanonicalType(CtxType)
678 == Context.getCanonicalType(ThisType)) ||
679 IsDerivedFrom(ThisType, CtxType)) {
680 // Build the implicit member access expression.
681 Expr *This = new CXXThisExpr(SourceLocation(),
682 MD->getThisType(Context));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000683 return Owned(new MemberExpr(This, true, cast<NamedDecl>(D),
684 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000685 }
686 }
687 }
688 }
689
Douglas Gregor8acb7272008-12-11 16:49:14 +0000690 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
692 if (MD->isStatic())
693 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000694 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
695 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000696 }
697
Douglas Gregor3257fb52008-12-22 05:46:06 +0000698 // Any other ways we could have found the field in a well-formed
699 // program would have been turned into implicit member expressions
700 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000701 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
702 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000703 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000704
Chris Lattner4b009652007-07-25 00:24:17 +0000705 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000706 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000707 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000708 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000709 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000711
Steve Naroffd6163f32008-09-05 22:11:13 +0000712 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000713 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000714 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
715 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000716
Steve Naroffd6163f32008-09-05 22:11:13 +0000717 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000718
Steve Naroffd6163f32008-09-05 22:11:13 +0000719 // check if referencing an identifier with __attribute__((deprecated)).
720 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000721 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
722
Douglas Gregor48840c72008-12-10 23:01:14 +0000723 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
724 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
725 Scope *CheckS = S;
726 while (CheckS) {
727 if (CheckS->isWithinElse() &&
728 CheckS->getControlParent()->isDeclScope(Var)) {
729 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000730 ExprError(Diag(Loc, diag::warn_value_always_false)
731 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000732 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733 ExprError(Diag(Loc, diag::warn_value_always_zero)
734 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000735 break;
736 }
737
738 // Move up one more control parent to check again.
739 CheckS = CheckS->getControlParent();
740 if (CheckS)
741 CheckS = CheckS->getParent();
742 }
743 }
744 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000745
746 // Only create DeclRefExpr's for valid Decl's.
747 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000748 return ExprError();
749
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000750 // If the identifier reference is inside a block, and it refers to a value
751 // that is outside the block, create a BlockDeclRefExpr instead of a
752 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
753 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000754 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000755 // We do not do this for things like enum constants, global variables, etc,
756 // as they do not get snapshotted.
757 //
758 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000759 // The BlocksAttr indicates the variable is bound by-reference.
760 if (VD->getAttr<BlocksAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000761 return Owned(new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
762 Loc, true));
763
Steve Naroff52059382008-10-10 01:28:17 +0000764 // Variable will be bound by-copy, make it const within the closure.
765 VD->getType().addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000766 return Owned(new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
767 Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000768 }
769 // If this reference is not in a block or if the referenced variable is
770 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000771
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000772 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000773 bool ValueDependent = false;
774 if (getLangOptions().CPlusPlus) {
775 // C++ [temp.dep.expr]p3:
776 // An id-expression is type-dependent if it contains:
777 // - an identifier that was declared with a dependent type,
778 if (VD->getType()->isDependentType())
779 TypeDependent = true;
780 // - FIXME: a template-id that is dependent,
781 // - a conversion-function-id that specifies a dependent type,
782 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
783 Name.getCXXNameType()->isDependentType())
784 TypeDependent = true;
785 // - a nested-name-specifier that contains a class-name that
786 // names a dependent type.
787 else if (SS && !SS->isEmpty()) {
788 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
789 DC; DC = DC->getParent()) {
790 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000791 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000792 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
793 if (Context.getTypeDeclType(Record)->isDependentType()) {
794 TypeDependent = true;
795 break;
796 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000797 }
798 }
799 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000800
Douglas Gregora5d84612008-12-10 20:57:37 +0000801 // C++ [temp.dep.constexpr]p2:
802 //
803 // An identifier is value-dependent if it is:
804 // - a name declared with a dependent type,
805 if (TypeDependent)
806 ValueDependent = true;
807 // - the name of a non-type template parameter,
808 else if (isa<NonTypeTemplateParmDecl>(VD))
809 ValueDependent = true;
810 // - a constant with integral or enumeration type and is
811 // initialized with an expression that is value-dependent
812 // (FIXME!).
813 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000814
Sebastian Redlcd883f72009-01-18 18:53:16 +0000815 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
816 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000817}
818
Sebastian Redlcd883f72009-01-18 18:53:16 +0000819Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
820 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000821 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000822
Chris Lattner4b009652007-07-25 00:24:17 +0000823 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000824 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000825 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
826 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
827 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000828 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000829
Chris Lattner7e637512008-01-12 08:14:25 +0000830 // Pre-defined identifiers are of type char[x], where x is the length of the
831 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000832 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000833 if (FunctionDecl *FD = getCurFunctionDecl())
834 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000835 else if (ObjCMethodDecl *MD = getCurMethodDecl())
836 Length = MD->getSynthesizedMethodSize();
837 else {
838 Diag(Loc, diag::ext_predef_outside_function);
839 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
840 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
841 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000842
843
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000844 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000845 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000846 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000847 return Owned(new PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000848}
849
Sebastian Redlcd883f72009-01-18 18:53:16 +0000850Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000851 llvm::SmallString<16> CharBuffer;
852 CharBuffer.resize(Tok.getLength());
853 const char *ThisTokBegin = &CharBuffer[0];
854 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000855
Chris Lattner4b009652007-07-25 00:24:17 +0000856 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
857 Tok.getLocation(), PP);
858 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000859 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000860
861 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
862
Sebastian Redlcd883f72009-01-18 18:53:16 +0000863 return Owned(new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
864 Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000865}
866
Sebastian Redlcd883f72009-01-18 18:53:16 +0000867Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
868 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000869 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
870 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000871 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
872 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000873 return Owned(new IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
874 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000875 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000876
Chris Lattner4b009652007-07-25 00:24:17 +0000877 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000878 // Add padding so that NumericLiteralParser can overread by one character.
879 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000880 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000881
Chris Lattner4b009652007-07-25 00:24:17 +0000882 // Get the spelling of the token, which eliminates trigraphs, etc.
883 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000884
Chris Lattner4b009652007-07-25 00:24:17 +0000885 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
886 Tok.getLocation(), PP);
887 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000888 return ExprError();
889
Chris Lattner1de66eb2007-08-26 03:42:43 +0000890 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000891
Chris Lattner1de66eb2007-08-26 03:42:43 +0000892 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000893 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000894 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000895 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000896 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000897 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000898 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000899 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000900
901 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
902
Ted Kremenekddedbe22007-11-29 00:56:49 +0000903 // isExact will be set by GetFloatValue().
904 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000905 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000906 Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000907
Chris Lattner1de66eb2007-08-26 03:42:43 +0000908 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000909 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000910 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000911 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000912
Neil Booth7421e9c2007-08-29 22:00:19 +0000913 // long long is a C99 feature.
914 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000915 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000916 Diag(Tok.getLocation(), diag::ext_longlong);
917
Chris Lattner4b009652007-07-25 00:24:17 +0000918 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000919 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000920
Chris Lattner4b009652007-07-25 00:24:17 +0000921 if (Literal.GetIntegerValue(ResultVal)) {
922 // If this value didn't fit into uintmax_t, warn and force to ull.
923 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000924 Ty = Context.UnsignedLongLongTy;
925 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000926 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000927 } else {
928 // If this value fits into a ULL, try to figure out what else it fits into
929 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000930
Chris Lattner4b009652007-07-25 00:24:17 +0000931 // Octal, Hexadecimal, and integers with a U suffix are allowed to
932 // be an unsigned int.
933 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
934
935 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000936 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000937 if (!Literal.isLong && !Literal.isLongLong) {
938 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000939 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000940
Chris Lattner4b009652007-07-25 00:24:17 +0000941 // Does it fit in a unsigned int?
942 if (ResultVal.isIntN(IntSize)) {
943 // Does it fit in a signed int?
944 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000945 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000946 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000947 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000948 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000949 }
Chris Lattner4b009652007-07-25 00:24:17 +0000950 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000951
Chris Lattner4b009652007-07-25 00:24:17 +0000952 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000953 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000954 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000955
Chris Lattner4b009652007-07-25 00:24:17 +0000956 // Does it fit in a unsigned long?
957 if (ResultVal.isIntN(LongSize)) {
958 // Does it fit in a signed long?
959 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000960 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000961 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000962 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000963 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000964 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965 }
966
Chris Lattner4b009652007-07-25 00:24:17 +0000967 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000968 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000969 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000970
Chris Lattner4b009652007-07-25 00:24:17 +0000971 // Does it fit in a unsigned long long?
972 if (ResultVal.isIntN(LongLongSize)) {
973 // Does it fit in a signed long long?
974 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000975 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000976 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000977 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000978 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000979 }
980 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000981
Chris Lattner4b009652007-07-25 00:24:17 +0000982 // If we still couldn't decide a type, we probably have something that
983 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000984 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000985 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000986 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000987 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000988 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000989
Chris Lattnere4068872008-05-09 05:59:00 +0000990 if (ResultVal.getBitWidth() != Width)
991 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000992 }
993
Chris Lattner48d7f382008-04-02 04:24:33 +0000994 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000995 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000996
Chris Lattner1de66eb2007-08-26 03:42:43 +0000997 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
998 if (Literal.isImaginary)
999 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001000
1001 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001002}
1003
Sebastian Redlcd883f72009-01-18 18:53:16 +00001004Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1005 SourceLocation R, ExprArg Val) {
1006 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001007 assert((E != 0) && "ActOnParenExpr() missing expr");
Sebastian Redlcd883f72009-01-18 18:53:16 +00001008 return Owned(new ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001009}
1010
1011/// The UsualUnaryConversions() function is *not* called by this routine.
1012/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001013bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1014 SourceLocation OpLoc,
1015 const SourceRange &ExprRange,
1016 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001017 // C99 6.5.3.4p1:
1018 if (isa<FunctionType>(exprType) && isSizeof)
1019 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001020 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +00001021 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001022 Diag(OpLoc, diag::ext_sizeof_void_type)
1023 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1024 else if (exprType->isIncompleteType())
1025 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
1026 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001027 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001028
1029 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001030}
1031
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001032/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1033/// the same for @c alignof and @c __alignof
1034/// Note that the ArgRange is invalid if isType is false.
1035Action::ExprResult
1036Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1037 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001038 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001039 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001040
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001041 QualType ArgTy;
1042 SourceRange Range;
1043 if (isType) {
1044 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1045 Range = ArgRange;
1046 } else {
1047 // Get the end location.
1048 Expr *ArgEx = (Expr *)TyOrEx;
1049 Range = ArgEx->getSourceRange();
1050 ArgTy = ArgEx->getType();
1051 }
1052
1053 // Verify that the operand is valid.
1054 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +00001055 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001056
1057 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1058 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
1059 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +00001060}
1061
Chris Lattner5110ad52007-08-24 21:41:10 +00001062QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001063 DefaultFunctionArrayConversion(V);
1064
Chris Lattnera16e42d2007-08-26 05:39:26 +00001065 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001066 if (const ComplexType *CT = V->getType()->getAsComplexType())
1067 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001068
1069 // Otherwise they pass through real integer and floating point types here.
1070 if (V->getType()->isArithmeticType())
1071 return V->getType();
1072
1073 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001074 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001075 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001076}
1077
1078
Chris Lattner4b009652007-07-25 00:24:17 +00001079
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001080Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001081 tok::TokenKind Kind,
1082 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001083 Expr *Arg = (Expr *)Input;
1084
Chris Lattner4b009652007-07-25 00:24:17 +00001085 UnaryOperator::Opcode Opc;
1086 switch (Kind) {
1087 default: assert(0 && "Unknown unary op!");
1088 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1089 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1090 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001091
1092 if (getLangOptions().CPlusPlus &&
1093 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1094 // Which overloaded operator?
1095 OverloadedOperatorKind OverOp =
1096 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1097
1098 // C++ [over.inc]p1:
1099 //
1100 // [...] If the function is a member function with one
1101 // parameter (which shall be of type int) or a non-member
1102 // function with two parameters (the second of which shall be
1103 // of type int), it defines the postfix increment operator ++
1104 // for objects of that type. When the postfix increment is
1105 // called as a result of using the ++ operator, the int
1106 // argument will have value zero.
1107 Expr *Args[2] = {
1108 Arg,
1109 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1110 /*isSigned=*/true),
1111 Context.IntTy, SourceLocation())
1112 };
1113
1114 // Build the candidate set for overloading
1115 OverloadCandidateSet CandidateSet;
1116 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1117
1118 // Perform overload resolution.
1119 OverloadCandidateSet::iterator Best;
1120 switch (BestViableFunction(CandidateSet, Best)) {
1121 case OR_Success: {
1122 // We found a built-in operator or an overloaded operator.
1123 FunctionDecl *FnDecl = Best->Function;
1124
1125 if (FnDecl) {
1126 // We matched an overloaded operator. Build a call to that
1127 // operator.
1128
1129 // Convert the arguments.
1130 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1131 if (PerformObjectArgumentInitialization(Arg, Method))
1132 return true;
1133 } else {
1134 // Convert the arguments.
1135 if (PerformCopyInitialization(Arg,
1136 FnDecl->getParamDecl(0)->getType(),
1137 "passing"))
1138 return true;
1139 }
1140
1141 // Determine the result type
1142 QualType ResultTy
1143 = FnDecl->getType()->getAsFunctionType()->getResultType();
1144 ResultTy = ResultTy.getNonReferenceType();
1145
1146 // Build the actual expression node.
1147 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1148 SourceLocation());
1149 UsualUnaryConversions(FnExpr);
1150
1151 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
1152 } else {
1153 // We matched a built-in operator. Convert the arguments, then
1154 // break out so that we will build the appropriate built-in
1155 // operator node.
1156 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1157 "passing"))
1158 return true;
1159
1160 break;
1161 }
1162 }
1163
1164 case OR_No_Viable_Function:
1165 // No viable function; fall through to handling this as a
1166 // built-in operator, which will produce an error message for us.
1167 break;
1168
1169 case OR_Ambiguous:
1170 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1171 << UnaryOperator::getOpcodeStr(Opc)
1172 << Arg->getSourceRange();
1173 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1174 return true;
1175 }
1176
1177 // Either we found no viable overloaded operator or we matched a
1178 // built-in operator. In either case, fall through to trying to
1179 // build a built-in operation.
1180 }
1181
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001182 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1183 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001184 if (result.isNull())
1185 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001186 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001187}
1188
1189Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +00001190ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001191 ExprTy *Idx, SourceLocation RLoc) {
1192 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
1193
Douglas Gregor80723c52008-11-19 17:17:41 +00001194 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +00001195 (LHSExp->getType()->isRecordType() ||
1196 LHSExp->getType()->isEnumeralType() ||
1197 RHSExp->getType()->isRecordType() ||
1198 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001199 // Add the appropriate overloaded operators (C++ [over.match.oper])
1200 // to the candidate set.
1201 OverloadCandidateSet CandidateSet;
1202 Expr *Args[2] = { LHSExp, RHSExp };
1203 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1204
1205 // Perform overload resolution.
1206 OverloadCandidateSet::iterator Best;
1207 switch (BestViableFunction(CandidateSet, Best)) {
1208 case OR_Success: {
1209 // We found a built-in operator or an overloaded operator.
1210 FunctionDecl *FnDecl = Best->Function;
1211
1212 if (FnDecl) {
1213 // We matched an overloaded operator. Build a call to that
1214 // operator.
1215
1216 // Convert the arguments.
1217 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1218 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1219 PerformCopyInitialization(RHSExp,
1220 FnDecl->getParamDecl(0)->getType(),
1221 "passing"))
1222 return true;
1223 } else {
1224 // Convert the arguments.
1225 if (PerformCopyInitialization(LHSExp,
1226 FnDecl->getParamDecl(0)->getType(),
1227 "passing") ||
1228 PerformCopyInitialization(RHSExp,
1229 FnDecl->getParamDecl(1)->getType(),
1230 "passing"))
1231 return true;
1232 }
1233
1234 // Determine the result type
1235 QualType ResultTy
1236 = FnDecl->getType()->getAsFunctionType()->getResultType();
1237 ResultTy = ResultTy.getNonReferenceType();
1238
1239 // Build the actual expression node.
1240 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1241 SourceLocation());
1242 UsualUnaryConversions(FnExpr);
1243
1244 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1245 } else {
1246 // We matched a built-in operator. Convert the arguments, then
1247 // break out so that we will build the appropriate built-in
1248 // operator node.
1249 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1250 "passing") ||
1251 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1252 "passing"))
1253 return true;
1254
1255 break;
1256 }
1257 }
1258
1259 case OR_No_Viable_Function:
1260 // No viable function; fall through to handling this as a
1261 // built-in operator, which will produce an error message for us.
1262 break;
1263
1264 case OR_Ambiguous:
1265 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1266 << "[]"
1267 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1268 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1269 return true;
1270 }
1271
1272 // Either we found no viable overloaded operator or we matched a
1273 // built-in operator. In either case, fall through to trying to
1274 // build a built-in operation.
1275 }
1276
Chris Lattner4b009652007-07-25 00:24:17 +00001277 // Perform default conversions.
1278 DefaultFunctionArrayConversion(LHSExp);
1279 DefaultFunctionArrayConversion(RHSExp);
1280
1281 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1282
1283 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001284 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001285 // in the subscript position. As a result, we need to derive the array base
1286 // and index from the expression types.
1287 Expr *BaseExpr, *IndexExpr;
1288 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001289 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001290 BaseExpr = LHSExp;
1291 IndexExpr = RHSExp;
1292 // FIXME: need to deal with const...
1293 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001294 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001295 // Handle the uncommon case of "123[Ptr]".
1296 BaseExpr = RHSExp;
1297 IndexExpr = LHSExp;
1298 // FIXME: need to deal with const...
1299 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001300 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1301 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001302 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001303
Chris Lattner4b009652007-07-25 00:24:17 +00001304 // FIXME: need to deal with const...
1305 ResultType = VTy->getElementType();
1306 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001307 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1308 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001309 }
1310 // C99 6.5.2.1p1
1311 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001312 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1313 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001314
1315 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1316 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001317 // void (*)(int)) and pointers to incomplete types. Functions are not
1318 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001319 if (!ResultType->isObjectType())
1320 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001321 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001322 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001323
1324 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1325}
1326
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001327QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001328CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001329 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001330 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001331
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001332 // The vector accessor can't exceed the number of elements.
1333 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001334
1335 // This flag determines whether or not the component is one of the four
1336 // special names that indicate a subset of exactly half the elements are
1337 // to be selected.
1338 bool HalvingSwizzle = false;
1339
1340 // This flag determines whether or not CompName has an 's' char prefix,
1341 // indicating that it is a string of hex values to be used as vector indices.
1342 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001343
1344 // Check that we've found one of the special components, or that the component
1345 // names must come from the same set.
1346 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001347 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1348 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001349 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001350 do
1351 compStr++;
1352 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001353 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001354 do
1355 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001356 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001357 }
Nate Begeman1486b502009-01-18 01:47:54 +00001358
1359 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001360 // We didn't get to the end of the string. This means the component names
1361 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001362 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1363 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001364 return QualType();
1365 }
Nate Begeman1486b502009-01-18 01:47:54 +00001366
1367 // Ensure no component accessor exceeds the width of the vector type it
1368 // operates on.
1369 if (!HalvingSwizzle) {
1370 compStr = CompName.getName();
1371
1372 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001373 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001374
1375 while (*compStr) {
1376 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1377 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1378 << baseType << SourceRange(CompLoc);
1379 return QualType();
1380 }
1381 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001382 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001383
Nate Begeman1486b502009-01-18 01:47:54 +00001384 // If this is a halving swizzle, verify that the base type has an even
1385 // number of elements.
1386 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001387 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001388 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001389 return QualType();
1390 }
1391
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001392 // The component accessor looks fine - now we need to compute the actual type.
1393 // The vector type is implied by the component accessor. For example,
1394 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001395 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001396 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001397 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1398 : CompName.getLength();
1399 if (HexSwizzle)
1400 CompSize--;
1401
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())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001484 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1485 BaseExpr, OpLoc)
1486 .release();
Douglas Gregor723d3332009-01-07 00:43:41 +00001487
Douglas Gregor82d44772008-12-20 23:49:58 +00001488 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1489 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001490 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001491 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1492 MemberType = Ref->getPointeeType();
1493 else {
1494 unsigned combinedQualifiers =
1495 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001496 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001497 combinedQualifiers &= ~QualType::Const;
1498 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1499 }
Eli Friedman76b49832008-02-06 22:48:16 +00001500
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001501 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor82d44772008-12-20 23:49:58 +00001502 MemberLoc, MemberType);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001503 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001504 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1505 Var->getType().getNonReferenceType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001506 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001507 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1508 MemberFn->getType());
1509 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001510 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001511 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1512 Context.OverloadTy);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001513 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001514 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1515 Enum->getType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001516 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001517 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1518 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman76b49832008-02-06 22:48:16 +00001519
Douglas Gregor82d44772008-12-20 23:49:58 +00001520 // We found a declaration kind that we didn't expect. This is a
1521 // generic error message that tells the user that she can't refer
1522 // to this member with '.' or '->'.
1523 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1524 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnera57cf472008-07-21 04:28:12 +00001525 }
1526
Chris Lattnere9d71612008-07-21 04:59:05 +00001527 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1528 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001529 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001530 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001531 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1532 BaseExpr,
1533 OpKind == tok::arrow);
1534 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1535 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001536 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001537 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001538 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001539 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001540 }
1541
Chris Lattnere9d71612008-07-21 04:59:05 +00001542 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1543 // pointer to a (potentially qualified) interface type.
1544 const PointerType *PTy;
1545 const ObjCInterfaceType *IFTy;
1546 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1547 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1548 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001549
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001550 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001551 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1552 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1553
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001554 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001555 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1556 E = IFTy->qual_end(); I != E; ++I)
1557 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1558 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001559
1560 // If that failed, look for an "implicit" property by seeing if the nullary
1561 // selector is implemented.
1562
1563 // FIXME: The logic for looking up nullary and unary selectors should be
1564 // shared with the code in ActOnInstanceMessage.
1565
1566 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1567 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1568
1569 // If this reference is in an @implementation, check for 'private' methods.
1570 if (!Getter)
1571 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1572 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1573 if (ObjCImplementationDecl *ImpDecl =
1574 ObjCImplementations[ClassDecl->getIdentifier()])
1575 Getter = ImpDecl->getInstanceMethod(Sel);
1576
Steve Naroff04151f32008-10-22 19:16:27 +00001577 // Look through local category implementations associated with the class.
1578 if (!Getter) {
1579 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1580 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1581 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1582 }
1583 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001584 if (Getter) {
1585 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001586 // will look for the matching setter, in case it is needed.
1587 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1588 &Member);
1589 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1590 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1591 if (!Setter) {
1592 // If this reference is in an @implementation, also check for 'private'
1593 // methods.
1594 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1595 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1596 if (ObjCImplementationDecl *ImpDecl =
1597 ObjCImplementations[ClassDecl->getIdentifier()])
1598 Setter = ImpDecl->getInstanceMethod(SetterSel);
1599 }
1600 // Look through local category implementations associated with the class.
1601 if (!Setter) {
1602 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1603 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1604 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1605 }
1606 }
1607
1608 // FIXME: we must check that the setter has property type.
1609 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001610 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001611 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001612
1613 return Diag(MemberLoc, diag::err_property_not_found) <<
1614 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001615 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001616 // Handle properties on qualified "id" protocols.
1617 const ObjCQualifiedIdType *QIdTy;
1618 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1619 // Check protocols on qualified interfaces.
1620 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001621 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001622 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1623 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001624 // Also must look for a getter name which uses property syntax.
1625 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1626 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1627 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1628 OpLoc, MemberLoc, NULL, 0);
1629 }
1630 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001631
1632 return Diag(MemberLoc, diag::err_property_not_found) <<
1633 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001634 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001635 // Handle 'field access' to vectors, such as 'V.xx'.
1636 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001637 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1638 if (ret.isNull())
1639 return true;
1640 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1641 }
1642
Chris Lattner8ba580c2008-11-19 05:08:23 +00001643 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001644 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001645}
1646
Douglas Gregor3257fb52008-12-22 05:46:06 +00001647/// ConvertArgumentsForCall - Converts the arguments specified in
1648/// Args/NumArgs to the parameter types of the function FDecl with
1649/// function prototype Proto. Call is the call expression itself, and
1650/// Fn is the function expression. For a C++ member function, this
1651/// routine does not attempt to convert the object argument. Returns
1652/// true if the call is ill-formed.
1653bool
1654Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1655 FunctionDecl *FDecl,
1656 const FunctionTypeProto *Proto,
1657 Expr **Args, unsigned NumArgs,
1658 SourceLocation RParenLoc) {
1659 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1660 // assignment, to the types of the corresponding parameter, ...
1661 unsigned NumArgsInProto = Proto->getNumArgs();
1662 unsigned NumArgsToCheck = NumArgs;
1663
1664 // If too few arguments are available (and we don't have default
1665 // arguments for the remaining parameters), don't make the call.
1666 if (NumArgs < NumArgsInProto) {
1667 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1668 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1669 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1670 // Use default arguments for missing arguments
1671 NumArgsToCheck = NumArgsInProto;
1672 Call->setNumArgs(NumArgsInProto);
1673 }
1674
1675 // If too many are passed and not variadic, error on the extras and drop
1676 // them.
1677 if (NumArgs > NumArgsInProto) {
1678 if (!Proto->isVariadic()) {
1679 Diag(Args[NumArgsInProto]->getLocStart(),
1680 diag::err_typecheck_call_too_many_args)
1681 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1682 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1683 Args[NumArgs-1]->getLocEnd());
1684 // This deletes the extra arguments.
1685 Call->setNumArgs(NumArgsInProto);
1686 }
1687 NumArgsToCheck = NumArgsInProto;
1688 }
1689
1690 // Continue to check argument types (even if we have too few/many args).
1691 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1692 QualType ProtoArgType = Proto->getArgType(i);
1693
1694 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001695 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001696 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001697
1698 // Pass the argument.
1699 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1700 return true;
1701 } else
1702 // We already type-checked the argument, so we know it works.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001703 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1704 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001705
Douglas Gregor3257fb52008-12-22 05:46:06 +00001706 Call->setArg(i, Arg);
1707 }
1708
1709 // If this is a variadic call, handle args passed through "...".
1710 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001711 VariadicCallType CallType = VariadicFunction;
1712 if (Fn->getType()->isBlockPointerType())
1713 CallType = VariadicBlock; // Block
1714 else if (isa<MemberExpr>(Fn))
1715 CallType = VariadicMethod;
1716
Douglas Gregor3257fb52008-12-22 05:46:06 +00001717 // Promote the arguments (C99 6.5.2.2p7).
1718 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1719 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001720 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001721 Call->setArg(i, Arg);
1722 }
1723 }
1724
1725 return false;
1726}
1727
Steve Naroff87d58b42007-09-16 03:34:24 +00001728/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001729/// This provides the location of the left/right parens and a list of comma
1730/// locations.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001731Action::ExprResult
1732Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1733 ExprTy **args, unsigned NumArgs,
1734 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001735 Expr *Fn = static_cast<Expr *>(fn);
1736 Expr **Args = reinterpret_cast<Expr**>(args);
1737 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001738 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001739 OverloadedFunctionDecl *Ovl = NULL;
1740
Douglas Gregora133e262008-12-06 00:22:45 +00001741 // Determine whether this is a dependent call inside a C++ template,
1742 // in which case we won't do any semantic analysis now.
1743 bool Dependent = false;
1744 if (Fn->isTypeDependent()) {
1745 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1746 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1747 Dependent = true;
1748 else {
1749 // Resolve the CXXDependentNameExpr to an actual identifier;
1750 // it wasn't really a dependent name after all.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001751 OwningExprResult Resolved
1752 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1753 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001754 /*HasTrailingLParen=*/true,
1755 /*SS=*/0,
1756 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001757 if (Resolved.isInvalid())
Douglas Gregora133e262008-12-06 00:22:45 +00001758 return true;
1759 else {
1760 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001761 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001762 }
1763 }
1764 } else
1765 Dependent = true;
1766 } else
1767 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1768
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001769 // FIXME: Will need to cache the results of name lookup (including
1770 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001771 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001772 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1773
Douglas Gregor3257fb52008-12-22 05:46:06 +00001774 // Determine whether this is a call to an object (C++ [over.call.object]).
1775 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1776 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1777 CommaLocs, RParenLoc);
1778
1779 // Determine whether this is a call to a member function.
1780 if (getLangOptions().CPlusPlus) {
1781 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1782 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1783 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1784 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1785 CommaLocs, RParenLoc);
1786 }
1787
Douglas Gregord2baafd2008-10-21 16:13:35 +00001788 // If we're directly calling a function or a set of overloaded
1789 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001790 DeclRefExpr *DRExpr = NULL;
1791 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1792 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1793 else
1794 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1795
1796 if (DRExpr) {
1797 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1798 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001799 }
1800
Douglas Gregord2baafd2008-10-21 16:13:35 +00001801 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001802 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1803 RParenLoc);
1804 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001805 return true;
1806
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001807 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001808 Expr *NewFn = 0;
1809 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1810 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1811 QDRExpr->getLocation(), false, false,
1812 QDRExpr->getSourceRange().getBegin());
1813 else
1814 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1815 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001816 Fn->Destroy(Context);
1817 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001818 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001819
1820 // Promote the function operand.
1821 UsualUnaryConversions(Fn);
1822
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001823 // Make the call expr early, before semantic checks. This guarantees cleanup
1824 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001825 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001826 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001827
Steve Naroffd6163f32008-09-05 22:11:13 +00001828 const FunctionType *FuncT;
1829 if (!Fn->getType()->isBlockPointerType()) {
1830 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1831 // have type pointer to function".
1832 const PointerType *PT = Fn->getType()->getAsPointerType();
1833 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001834 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001835 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001836 FuncT = PT->getPointeeType()->getAsFunctionType();
1837 } else { // This is a block call.
1838 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1839 getAsFunctionType();
1840 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001841 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001842 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001843 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001844
1845 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001846 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001847
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001848 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001849 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1850 RParenLoc))
1851 return true;
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001852 } else {
1853 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1854
Steve Naroffdb65e052007-08-28 23:30:39 +00001855 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001856 for (unsigned i = 0; i != NumArgs; i++) {
1857 Expr *Arg = Args[i];
1858 DefaultArgumentPromotion(Arg);
1859 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001860 }
Chris Lattner4b009652007-07-25 00:24:17 +00001861 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001862
Douglas Gregor3257fb52008-12-22 05:46:06 +00001863 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1864 if (!Method->isStatic())
1865 return Diag(LParenLoc, diag::err_member_call_without_object)
1866 << Fn->getSourceRange();
1867
Chris Lattner2e64c072007-08-10 20:18:51 +00001868 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001869 if (FDecl)
1870 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001871
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001872 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001873}
1874
1875Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001876ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001877 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001878 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001879 QualType literalType = QualType::getFromOpaquePtr(Ty);
1880 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001881 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001882 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001883
Eli Friedman8c2173d2008-05-20 05:22:08 +00001884 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001885 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001886 return Diag(LParenLoc, diag::err_variable_object_no_init)
1887 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001888 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001889 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001890 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001891 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001892 }
1893
Douglas Gregor6428e762008-11-05 15:29:30 +00001894 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001895 DeclarationName(), /*FIXME:DirectInit=*/false))
Steve Naroff92590f92008-01-09 20:58:06 +00001896 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001897
Chris Lattnere5cb5862008-12-04 23:50:19 +00001898 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001899 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001900 if (CheckForConstantInitializer(literalExpr, literalType))
1901 return true;
1902 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001903 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1904 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001905}
1906
1907Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001908ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001909 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001910 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001911 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001912
Steve Naroff0acc9c92007-09-15 18:49:24 +00001913 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001914 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001915
Chris Lattner71ca8c82008-10-26 23:43:26 +00001916 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1917 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001918 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1919 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001920}
1921
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001922/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001923bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001924 UsualUnaryConversions(castExpr);
1925
1926 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1927 // type needs to be scalar.
1928 if (castType->isVoidType()) {
1929 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001930 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1931 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001932 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001933 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1934 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1935 (castType->isStructureType() || castType->isUnionType())) {
1936 // GCC struct/union extension: allow cast to self.
1937 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1938 << castType << castExpr->getSourceRange();
1939 } else if (castType->isUnionType()) {
1940 // GCC cast to union extension
1941 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1942 RecordDecl::field_iterator Field, FieldEnd;
1943 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1944 Field != FieldEnd; ++Field) {
1945 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1946 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1947 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1948 << castExpr->getSourceRange();
1949 break;
1950 }
1951 }
1952 if (Field == FieldEnd)
1953 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1954 << castExpr->getType() << castExpr->getSourceRange();
1955 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001956 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001957 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001958 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001959 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001960 } else if (!castExpr->getType()->isScalarType() &&
1961 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001962 return Diag(castExpr->getLocStart(),
1963 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001964 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001965 } else if (castExpr->getType()->isVectorType()) {
1966 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1967 return true;
1968 } else if (castType->isVectorType()) {
1969 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1970 return true;
1971 }
1972 return false;
1973}
1974
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001975bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001976 assert(VectorTy->isVectorType() && "Not a vector type!");
1977
1978 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001979 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001980 return Diag(R.getBegin(),
1981 Ty->isVectorType() ?
1982 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001983 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001984 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001985 } else
1986 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001987 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001988 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001989
1990 return false;
1991}
1992
Chris Lattner4b009652007-07-25 00:24:17 +00001993Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001994ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001995 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001996 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001997
1998 Expr *castExpr = static_cast<Expr*>(Op);
1999 QualType castType = QualType::getFromOpaquePtr(Ty);
2000
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002001 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2002 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00002003 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002004}
2005
Chris Lattner98a425c2007-11-26 01:40:58 +00002006/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2007/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002008inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2009 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2010 UsualUnaryConversions(cond);
2011 UsualUnaryConversions(lex);
2012 UsualUnaryConversions(rex);
2013 QualType condT = cond->getType();
2014 QualType lexT = lex->getType();
2015 QualType rexT = rex->getType();
2016
2017 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002018 if (!cond->isTypeDependent()) {
2019 if (!condT->isScalarType()) { // C99 6.5.15p2
2020 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2021 return QualType();
2022 }
Chris Lattner4b009652007-07-25 00:24:17 +00002023 }
Chris Lattner992ae932008-01-06 22:42:25 +00002024
2025 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002026 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2027 return Context.DependentTy;
2028
Chris Lattner992ae932008-01-06 22:42:25 +00002029 // If both operands have arithmetic type, do the usual arithmetic conversions
2030 // to find a common type: C99 6.5.15p3,5.
2031 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002032 UsualArithmeticConversions(lex, rex);
2033 return lex->getType();
2034 }
Chris Lattner992ae932008-01-06 22:42:25 +00002035
2036 // If both operands are the same structure or union type, the result is that
2037 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002038 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002039 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002040 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002041 // "If both the operands have structure or union type, the result has
2042 // that type." This implies that CV qualifiers are dropped.
2043 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002044 }
Chris Lattner992ae932008-01-06 22:42:25 +00002045
2046 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002047 // The following || allows only one side to be void (a GCC-ism).
2048 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002049 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002050 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2051 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002052 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002053 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2054 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002055 ImpCastExprToType(lex, Context.VoidTy);
2056 ImpCastExprToType(rex, Context.VoidTy);
2057 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002058 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002059 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2060 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002061 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2062 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002063 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002064 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002065 return lexT;
2066 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002067 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2068 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002069 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002070 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002071 return rexT;
2072 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002073 // Handle the case where both operands are pointers before we handle null
2074 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002075 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2076 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2077 // get the "pointed to" types
2078 QualType lhptee = LHSPT->getPointeeType();
2079 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002080
Chris Lattner71225142007-07-31 21:27:01 +00002081 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2082 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002083 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002084 // Figure out necessary qualifiers (C99 6.5.15p6)
2085 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002086 QualType destType = Context.getPointerType(destPointee);
2087 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2088 ImpCastExprToType(rex, destType); // promote to void*
2089 return destType;
2090 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002091 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002092 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002093 QualType destType = Context.getPointerType(destPointee);
2094 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2095 ImpCastExprToType(rex, destType); // promote to void*
2096 return destType;
2097 }
Chris Lattner4b009652007-07-25 00:24:17 +00002098
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002099 QualType compositeType = lexT;
2100
2101 // If either type is an Objective-C object type then check
2102 // compatibility according to Objective-C.
2103 if (Context.isObjCObjectPointerType(lexT) ||
2104 Context.isObjCObjectPointerType(rexT)) {
2105 // If both operands are interfaces and either operand can be
2106 // assigned to the other, use that type as the composite
2107 // type. This allows
2108 // xxx ? (A*) a : (B*) b
2109 // where B is a subclass of A.
2110 //
2111 // Additionally, as for assignment, if either type is 'id'
2112 // allow silent coercion. Finally, if the types are
2113 // incompatible then make sure to use 'id' as the composite
2114 // type so the result is acceptable for sending messages to.
2115
2116 // FIXME: This code should not be localized to here. Also this
2117 // should use a compatible check instead of abusing the
2118 // canAssignObjCInterfaces code.
2119 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2120 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2121 if (LHSIface && RHSIface &&
2122 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2123 compositeType = lexT;
2124 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002125 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002126 compositeType = rexT;
2127 } else if (Context.isObjCIdType(lhptee) ||
2128 Context.isObjCIdType(rhptee)) {
2129 // FIXME: This code looks wrong, because isObjCIdType checks
2130 // the struct but getObjCIdType returns the pointer to
2131 // struct. This is horrible and should be fixed.
2132 compositeType = Context.getObjCIdType();
2133 } else {
2134 QualType incompatTy = Context.getObjCIdType();
2135 ImpCastExprToType(lex, incompatTy);
2136 ImpCastExprToType(rex, incompatTy);
2137 return incompatTy;
2138 }
2139 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2140 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002141 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002142 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002143 // In this situation, we assume void* type. No especially good
2144 // reason, but this is what gcc does, and we do have to pick
2145 // to get a consistent AST.
2146 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002147 ImpCastExprToType(lex, incompatTy);
2148 ImpCastExprToType(rex, incompatTy);
2149 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002150 }
2151 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002152 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2153 // differently qualified versions of compatible types, the result type is
2154 // a pointer to an appropriately qualified version of the *composite*
2155 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002156 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002157 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002158 ImpCastExprToType(lex, compositeType);
2159 ImpCastExprToType(rex, compositeType);
2160 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002161 }
Chris Lattner4b009652007-07-25 00:24:17 +00002162 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002163 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2164 // evaluates to "struct objc_object *" (and is handled above when comparing
2165 // id with statically typed objects).
2166 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2167 // GCC allows qualified id and any Objective-C type to devolve to
2168 // id. Currently localizing to here until clear this should be
2169 // part of ObjCQualifiedIdTypesAreCompatible.
2170 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2171 (lexT->isObjCQualifiedIdType() &&
2172 Context.isObjCObjectPointerType(rexT)) ||
2173 (rexT->isObjCQualifiedIdType() &&
2174 Context.isObjCObjectPointerType(lexT))) {
2175 // FIXME: This is not the correct composite type. This only
2176 // happens to work because id can more or less be used anywhere,
2177 // however this may change the type of method sends.
2178 // FIXME: gcc adds some type-checking of the arguments and emits
2179 // (confusing) incompatible comparison warnings in some
2180 // cases. Investigate.
2181 QualType compositeType = Context.getObjCIdType();
2182 ImpCastExprToType(lex, compositeType);
2183 ImpCastExprToType(rex, compositeType);
2184 return compositeType;
2185 }
2186 }
2187
Steve Naroff3eac7692008-09-10 19:17:48 +00002188 // Selection between block pointer types is ok as long as they are the same.
2189 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2190 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2191 return lexT;
2192
Chris Lattner992ae932008-01-06 22:42:25 +00002193 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002194 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002195 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002196 return QualType();
2197}
2198
Steve Naroff87d58b42007-09-16 03:34:24 +00002199/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002200/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00002201Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002202 SourceLocation ColonLoc,
2203 ExprTy *Cond, ExprTy *LHS,
2204 ExprTy *RHS) {
2205 Expr *CondExpr = (Expr *) Cond;
2206 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00002207
2208 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2209 // was the condition.
2210 bool isLHSNull = LHSExpr == 0;
2211 if (isLHSNull)
2212 LHSExpr = CondExpr;
2213
Chris Lattner4b009652007-07-25 00:24:17 +00002214 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2215 RHSExpr, QuestionLoc);
2216 if (result.isNull())
2217 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00002218 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2219 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00002220}
2221
Chris Lattner4b009652007-07-25 00:24:17 +00002222
2223// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2224// being closely modeled after the C99 spec:-). The odd characteristic of this
2225// routine is it effectively iqnores the qualifiers on the top level pointee.
2226// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2227// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002228Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002229Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2230 QualType lhptee, rhptee;
2231
2232 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002233 lhptee = lhsType->getAsPointerType()->getPointeeType();
2234 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002235
2236 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002237 lhptee = Context.getCanonicalType(lhptee);
2238 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002239
Chris Lattner005ed752008-01-04 18:04:52 +00002240 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002241
2242 // C99 6.5.16.1p1: This following citation is common to constraints
2243 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2244 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002245 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002246 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002247 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002248
2249 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2250 // incomplete type and the other is a pointer to a qualified or unqualified
2251 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002252 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002253 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002254 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002255
2256 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002257 assert(rhptee->isFunctionType());
2258 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002259 }
2260
2261 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002262 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002263 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002264
2265 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002266 assert(lhptee->isFunctionType());
2267 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002268 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002269
2270 // Check for ObjC interfaces
2271 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2272 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2273 if (LHSIface && RHSIface &&
2274 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2275 return ConvTy;
2276
2277 // ID acts sort of like void* for ObjC interfaces
2278 if (LHSIface && Context.isObjCIdType(rhptee))
2279 return ConvTy;
2280 if (RHSIface && Context.isObjCIdType(lhptee))
2281 return ConvTy;
2282
Chris Lattner4b009652007-07-25 00:24:17 +00002283 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2284 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002285 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2286 rhptee.getUnqualifiedType()))
2287 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002288 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002289}
2290
Steve Naroff3454b6c2008-09-04 15:10:53 +00002291/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2292/// block pointer types are compatible or whether a block and normal pointer
2293/// are compatible. It is more restrict than comparing two function pointer
2294// types.
2295Sema::AssignConvertType
2296Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2297 QualType rhsType) {
2298 QualType lhptee, rhptee;
2299
2300 // get the "pointed to" type (ignoring qualifiers at the top level)
2301 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2302 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2303
2304 // make sure we operate on the canonical type
2305 lhptee = Context.getCanonicalType(lhptee);
2306 rhptee = Context.getCanonicalType(rhptee);
2307
2308 AssignConvertType ConvTy = Compatible;
2309
2310 // For blocks we enforce that qualifiers are identical.
2311 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2312 ConvTy = CompatiblePointerDiscardsQualifiers;
2313
2314 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2315 return IncompatibleBlockPointer;
2316 return ConvTy;
2317}
2318
Chris Lattner4b009652007-07-25 00:24:17 +00002319/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2320/// has code to accommodate several GCC extensions when type checking
2321/// pointers. Here are some objectionable examples that GCC considers warnings:
2322///
2323/// int a, *pint;
2324/// short *pshort;
2325/// struct foo *pfoo;
2326///
2327/// pint = pshort; // warning: assignment from incompatible pointer type
2328/// a = pint; // warning: assignment makes integer from pointer without a cast
2329/// pint = a; // warning: assignment makes pointer from integer without a cast
2330/// pint = pfoo; // warning: assignment from incompatible pointer type
2331///
2332/// As a result, the code for dealing with pointers is more complex than the
2333/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002334///
Chris Lattner005ed752008-01-04 18:04:52 +00002335Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002336Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002337 // Get canonical types. We're not formatting these types, just comparing
2338 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002339 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2340 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002341
2342 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002343 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002344
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002345 // If the left-hand side is a reference type, then we are in a
2346 // (rare!) case where we've allowed the use of references in C,
2347 // e.g., as a parameter type in a built-in function. In this case,
2348 // just make sure that the type referenced is compatible with the
2349 // right-hand side type. The caller is responsible for adjusting
2350 // lhsType so that the resulting expression does not have reference
2351 // type.
2352 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2353 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002354 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002355 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002356 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002357
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002358 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2359 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002360 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002361 // Relax integer conversions like we do for pointers below.
2362 if (rhsType->isIntegerType())
2363 return IntToPointer;
2364 if (lhsType->isIntegerType())
2365 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002366 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002367 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002368
Nate Begemanc5f0f652008-07-14 18:02:46 +00002369 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002370 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002371 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2372 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002373 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002374
Nate Begemanc5f0f652008-07-14 18:02:46 +00002375 // If we are allowing lax vector conversions, and LHS and RHS are both
2376 // vectors, the total size only needs to be the same. This is a bitcast;
2377 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002378 if (getLangOptions().LaxVectorConversions &&
2379 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002380 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2381 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002382 }
2383 return Incompatible;
2384 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002385
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002386 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002387 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002388
Chris Lattner390564e2008-04-07 06:49:41 +00002389 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002390 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002391 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002392
Chris Lattner390564e2008-04-07 06:49:41 +00002393 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002394 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002395
Steve Naroffa982c712008-09-29 18:10:17 +00002396 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002397 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002398 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002399
2400 // Treat block pointers as objects.
2401 if (getLangOptions().ObjC1 &&
2402 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2403 return Compatible;
2404 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002405 return Incompatible;
2406 }
2407
2408 if (isa<BlockPointerType>(lhsType)) {
2409 if (rhsType->isIntegerType())
2410 return IntToPointer;
2411
Steve Naroffa982c712008-09-29 18:10:17 +00002412 // Treat block pointers as objects.
2413 if (getLangOptions().ObjC1 &&
2414 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2415 return Compatible;
2416
Steve Naroff3454b6c2008-09-04 15:10:53 +00002417 if (rhsType->isBlockPointerType())
2418 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2419
2420 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2421 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002422 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002423 }
Chris Lattner1853da22008-01-04 23:18:45 +00002424 return Incompatible;
2425 }
2426
Chris Lattner390564e2008-04-07 06:49:41 +00002427 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002428 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002429 if (lhsType == Context.BoolTy)
2430 return Compatible;
2431
2432 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002433 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002434
Chris Lattner390564e2008-04-07 06:49:41 +00002435 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002436 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002437
2438 if (isa<BlockPointerType>(lhsType) &&
2439 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002440 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002441 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002442 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002443
Chris Lattner1853da22008-01-04 23:18:45 +00002444 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002445 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002446 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002447 }
2448 return Incompatible;
2449}
2450
Chris Lattner005ed752008-01-04 18:04:52 +00002451Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002452Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002453 if (getLangOptions().CPlusPlus) {
2454 if (!lhsType->isRecordType()) {
2455 // C++ 5.17p3: If the left operand is not of class type, the
2456 // expression is implicitly converted (C++ 4) to the
2457 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002458 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2459 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002460 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002461 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002462 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002463 }
2464
2465 // FIXME: Currently, we fall through and treat C++ classes like C
2466 // structures.
2467 }
2468
Steve Naroffcdee22d2007-11-27 17:58:44 +00002469 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2470 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002471 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2472 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002473 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002474 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002475 return Compatible;
2476 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002477
2478 // We don't allow conversion of non-null-pointer constants to integers.
2479 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2480 return IntToBlockPointer;
2481
Chris Lattner5f505bf2007-10-16 02:55:40 +00002482 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002483 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002484 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002485 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002486 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002487 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002488 if (!lhsType->isReferenceType())
2489 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002490
Chris Lattner005ed752008-01-04 18:04:52 +00002491 Sema::AssignConvertType result =
2492 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002493
2494 // C99 6.5.16.1p2: The value of the right operand is converted to the
2495 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002496 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2497 // so that we can use references in built-in functions even in C.
2498 // The getNonReferenceType() call makes sure that the resulting expression
2499 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002500 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002501 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002502 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002503}
2504
Chris Lattner005ed752008-01-04 18:04:52 +00002505Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002506Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2507 return CheckAssignmentConstraints(lhsType, rhsType);
2508}
2509
Chris Lattner1eafdea2008-11-18 01:30:42 +00002510QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002511 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002512 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002513 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002514 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002515}
2516
Chris Lattner1eafdea2008-11-18 01:30:42 +00002517inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002518 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002519 // For conversion purposes, we ignore any qualifiers.
2520 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002521 QualType lhsType =
2522 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2523 QualType rhsType =
2524 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002525
Nate Begemanc5f0f652008-07-14 18:02:46 +00002526 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002527 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002528 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002529
Nate Begemanc5f0f652008-07-14 18:02:46 +00002530 // Handle the case of a vector & extvector type of the same size and element
2531 // type. It would be nice if we only had one vector type someday.
2532 if (getLangOptions().LaxVectorConversions)
2533 if (const VectorType *LV = lhsType->getAsVectorType())
2534 if (const VectorType *RV = rhsType->getAsVectorType())
2535 if (LV->getElementType() == RV->getElementType() &&
2536 LV->getNumElements() == RV->getNumElements())
2537 return lhsType->isExtVectorType() ? lhsType : rhsType;
2538
2539 // If the lhs is an extended vector and the rhs is a scalar of the same type
2540 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002541 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002542 QualType eltType = V->getElementType();
2543
2544 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2545 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2546 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002547 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002548 return lhsType;
2549 }
2550 }
2551
Nate Begemanc5f0f652008-07-14 18:02:46 +00002552 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002553 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002554 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002555 QualType eltType = V->getElementType();
2556
2557 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2558 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2559 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002560 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002561 return rhsType;
2562 }
2563 }
2564
Chris Lattner4b009652007-07-25 00:24:17 +00002565 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002566 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002567 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002568 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002569 return QualType();
2570}
2571
2572inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002573 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002574{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002575 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002576 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002577
Steve Naroff8f708362007-08-24 19:07:16 +00002578 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002579
Chris Lattner4b009652007-07-25 00:24:17 +00002580 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002581 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002582 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002583}
2584
2585inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002586 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002587{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002588 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2589 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2590 return CheckVectorOperands(Loc, lex, rex);
2591 return InvalidOperands(Loc, lex, rex);
2592 }
Chris Lattner4b009652007-07-25 00:24:17 +00002593
Steve Naroff8f708362007-08-24 19:07:16 +00002594 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002595
Chris Lattner4b009652007-07-25 00:24:17 +00002596 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002597 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002598 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002599}
2600
2601inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002602 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002603{
2604 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002605 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002606
Steve Naroff8f708362007-08-24 19:07:16 +00002607 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002608
Chris Lattner4b009652007-07-25 00:24:17 +00002609 // handle the common case first (both operands are arithmetic).
2610 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002611 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002612
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002613 // Put any potential pointer into PExp
2614 Expr* PExp = lex, *IExp = rex;
2615 if (IExp->getType()->isPointerType())
2616 std::swap(PExp, IExp);
2617
2618 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2619 if (IExp->getType()->isIntegerType()) {
2620 // Check for arithmetic on pointers to incomplete types
2621 if (!PTy->getPointeeType()->isObjectType()) {
2622 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002623 Diag(Loc, diag::ext_gnu_void_ptr)
2624 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002625 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002626 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002627 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002628 return QualType();
2629 }
2630 }
2631 return PExp->getType();
2632 }
2633 }
2634
Chris Lattner1eafdea2008-11-18 01:30:42 +00002635 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002636}
2637
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002638// C99 6.5.6
2639QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002640 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002641 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002642 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002643
Steve Naroff8f708362007-08-24 19:07:16 +00002644 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002645
Chris Lattnerf6da2912007-12-09 21:53:25 +00002646 // Enforce type constraints: C99 6.5.6p3.
2647
2648 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002649 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002650 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002651
2652 // Either ptr - int or ptr - ptr.
2653 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002654 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002655
Chris Lattnerf6da2912007-12-09 21:53:25 +00002656 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002657 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002658 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002659 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002660 Diag(Loc, diag::ext_gnu_void_ptr)
2661 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002662 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002663 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002664 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002665 return QualType();
2666 }
2667 }
2668
2669 // The result type of a pointer-int computation is the pointer type.
2670 if (rex->getType()->isIntegerType())
2671 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002672
Chris Lattnerf6da2912007-12-09 21:53:25 +00002673 // Handle pointer-pointer subtractions.
2674 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002675 QualType rpointee = RHSPTy->getPointeeType();
2676
Chris Lattnerf6da2912007-12-09 21:53:25 +00002677 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002678 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002679 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002680 if (rpointee->isVoidType()) {
2681 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002682 Diag(Loc, diag::ext_gnu_void_ptr)
2683 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002684 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002685 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002686 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002687 return QualType();
2688 }
2689 }
2690
2691 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002692 if (!Context.typesAreCompatible(
2693 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2694 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002695 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002696 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002697 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002698 return QualType();
2699 }
2700
2701 return Context.getPointerDiffType();
2702 }
2703 }
2704
Chris Lattner1eafdea2008-11-18 01:30:42 +00002705 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002706}
2707
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002708// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002709QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002710 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002711 // C99 6.5.7p2: Each of the operands shall have integer type.
2712 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002713 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002714
Chris Lattner2c8bff72007-12-12 05:47:28 +00002715 // Shifts don't perform usual arithmetic conversions, they just do integer
2716 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002717 if (!isCompAssign)
2718 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002719 UsualUnaryConversions(rex);
2720
2721 // "The type of the result is that of the promoted left operand."
2722 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002723}
2724
Eli Friedman0d9549b2008-08-22 00:56:42 +00002725static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2726 ASTContext& Context) {
2727 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2728 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2729 // ID acts sort of like void* for ObjC interfaces
2730 if (LHSIface && Context.isObjCIdType(RHS))
2731 return true;
2732 if (RHSIface && Context.isObjCIdType(LHS))
2733 return true;
2734 if (!LHSIface || !RHSIface)
2735 return false;
2736 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2737 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2738}
2739
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002740// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002741QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002742 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002743 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002744 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002745
Chris Lattner254f3bc2007-08-26 01:18:55 +00002746 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002747 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2748 UsualArithmeticConversions(lex, rex);
2749 else {
2750 UsualUnaryConversions(lex);
2751 UsualUnaryConversions(rex);
2752 }
Chris Lattner4b009652007-07-25 00:24:17 +00002753 QualType lType = lex->getType();
2754 QualType rType = rex->getType();
2755
Ted Kremenek486509e2007-10-29 17:13:39 +00002756 // For non-floating point types, check for self-comparisons of the form
2757 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2758 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002759 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002760 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2761 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002762 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002763 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002764 }
2765
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002766 // The result of comparisons is 'bool' in C++, 'int' in C.
2767 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2768
Chris Lattner254f3bc2007-08-26 01:18:55 +00002769 if (isRelational) {
2770 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002771 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002772 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002773 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002774 if (lType->isFloatingType()) {
2775 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002776 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002777 }
2778
Chris Lattner254f3bc2007-08-26 01:18:55 +00002779 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002780 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002781 }
Chris Lattner4b009652007-07-25 00:24:17 +00002782
Chris Lattner22be8422007-08-26 01:10:14 +00002783 bool LHSIsNull = lex->isNullPointerConstant(Context);
2784 bool RHSIsNull = rex->isNullPointerConstant(Context);
2785
Chris Lattner254f3bc2007-08-26 01:18:55 +00002786 // All of the following pointer related warnings are GCC extensions, except
2787 // when handling null pointer constants. One day, we can consider making them
2788 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002789 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002790 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002791 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002792 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002793 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002794
Steve Naroff3b435622007-11-13 14:57:38 +00002795 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002796 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2797 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002798 RCanPointeeTy.getUnqualifiedType()) &&
2799 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002800 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002801 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002802 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002803 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002804 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002805 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002806 // Handle block pointer types.
2807 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2808 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2809 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2810
2811 if (!LHSIsNull && !RHSIsNull &&
2812 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002813 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002814 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002815 }
2816 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002817 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002818 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002819 // Allow block pointers to be compared with null pointer constants.
2820 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2821 (lType->isPointerType() && rType->isBlockPointerType())) {
2822 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002823 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002824 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002825 }
2826 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002827 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002828 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002829
Steve Naroff936c4362008-06-03 14:04:54 +00002830 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002831 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002832 const PointerType *LPT = lType->getAsPointerType();
2833 const PointerType *RPT = rType->getAsPointerType();
2834 bool LPtrToVoid = LPT ?
2835 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2836 bool RPtrToVoid = RPT ?
2837 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2838
2839 if (!LPtrToVoid && !RPtrToVoid &&
2840 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002841 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002842 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002843 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002844 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002845 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002846 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002847 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002848 }
Steve Naroff936c4362008-06-03 14:04:54 +00002849 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2850 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002851 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002852 } else {
2853 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002854 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002855 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002856 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002857 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002858 }
Steve Naroff936c4362008-06-03 14:04:54 +00002859 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002860 }
Steve Naroff936c4362008-06-03 14:04:54 +00002861 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2862 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002863 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002864 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002865 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002866 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002867 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002868 }
Steve Naroff936c4362008-06-03 14:04:54 +00002869 if (lType->isIntegerType() &&
2870 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002871 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002872 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002873 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002874 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002875 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002876 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002877 // Handle block pointers.
2878 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2879 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002880 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002881 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002882 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002883 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002884 }
2885 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2886 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002887 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002888 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002889 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002890 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002891 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002892 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002893}
2894
Nate Begemanc5f0f652008-07-14 18:02:46 +00002895/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2896/// operates on extended vector types. Instead of producing an IntTy result,
2897/// like a scalar comparison, a vector comparison produces a vector of integer
2898/// types.
2899QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002900 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002901 bool isRelational) {
2902 // Check to make sure we're operating on vectors of the same type and width,
2903 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002904 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002905 if (vType.isNull())
2906 return vType;
2907
2908 QualType lType = lex->getType();
2909 QualType rType = rex->getType();
2910
2911 // For non-floating point types, check for self-comparisons of the form
2912 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2913 // often indicate logic errors in the program.
2914 if (!lType->isFloatingType()) {
2915 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2916 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2917 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002918 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002919 }
2920
2921 // Check for comparisons of floating point operands using != and ==.
2922 if (!isRelational && lType->isFloatingType()) {
2923 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002924 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002925 }
2926
2927 // Return the type for the comparison, which is the same as vector type for
2928 // integer vectors, or an integer type of identical size and number of
2929 // elements for floating point vectors.
2930 if (lType->isIntegerType())
2931 return lType;
2932
2933 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00002934 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00002935 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00002936 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00002937 else if (TypeSize == Context.getTypeSize(Context.LongTy))
2938 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
2939
2940 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
2941 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00002942 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2943}
2944
Chris Lattner4b009652007-07-25 00:24:17 +00002945inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002946 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002947{
2948 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002949 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002950
Steve Naroff8f708362007-08-24 19:07:16 +00002951 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002952
2953 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002954 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002955 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002956}
2957
2958inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002959 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002960{
2961 UsualUnaryConversions(lex);
2962 UsualUnaryConversions(rex);
2963
Eli Friedmanbea3f842008-05-13 20:16:47 +00002964 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002965 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002966 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002967}
2968
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00002969/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
2970/// is a read-only property; return true if so. A readonly property expression
2971/// depends on various declarations and thus must be treated specially.
2972///
2973static bool IsReadonlyProperty(Expr *E, Sema &S)
2974{
2975 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
2976 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
2977 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
2978 QualType BaseType = PropExpr->getBase()->getType();
2979 if (const PointerType *PTy = BaseType->getAsPointerType())
2980 if (const ObjCInterfaceType *IFTy =
2981 PTy->getPointeeType()->getAsObjCInterfaceType())
2982 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
2983 if (S.isPropertyReadonly(PDecl, IFace))
2984 return true;
2985 }
2986 }
2987 return false;
2988}
2989
Chris Lattner4c2642c2008-11-18 01:22:49 +00002990/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2991/// emit an error and return true. If so, return false.
2992static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00002993 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2994 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
2995 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002996 if (IsLV == Expr::MLV_Valid)
2997 return false;
2998
2999 unsigned Diag = 0;
3000 bool NeedType = false;
3001 switch (IsLV) { // C99 6.5.16p2
3002 default: assert(0 && "Unknown result from isModifiableLvalue!");
3003 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003004 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003005 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3006 NeedType = true;
3007 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003008 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003009 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3010 NeedType = true;
3011 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003012 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003013 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3014 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003015 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003016 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3017 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003018 case Expr::MLV_IncompleteType:
3019 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003020 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
3021 NeedType = true;
3022 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003023 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003024 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3025 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003026 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003027 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3028 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003029 case Expr::MLV_ReadonlyProperty:
3030 Diag = diag::error_readonly_property_assignment;
3031 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003032 case Expr::MLV_NoSetterProperty:
3033 Diag = diag::error_nosetter_property_assignment;
3034 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003035 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003036
Chris Lattner4c2642c2008-11-18 01:22:49 +00003037 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003038 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003039 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003040 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003041 return true;
3042}
3043
3044
3045
3046// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003047QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3048 SourceLocation Loc,
3049 QualType CompoundType) {
3050 // Verify that LHS is a modifiable lvalue, and emit error if not.
3051 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003052 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003053
3054 QualType LHSType = LHS->getType();
3055 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003056
Chris Lattner005ed752008-01-04 18:04:52 +00003057 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003058 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003059 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003060 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003061 // Special case of NSObject attributes on c-style pointer types.
3062 if (ConvTy == IncompatiblePointer &&
3063 ((Context.isObjCNSObjectType(LHSType) &&
3064 Context.isObjCObjectPointerType(RHSType)) ||
3065 (Context.isObjCNSObjectType(RHSType) &&
3066 Context.isObjCObjectPointerType(LHSType))))
3067 ConvTy = Compatible;
3068
Chris Lattner34c85082008-08-21 18:04:13 +00003069 // If the RHS is a unary plus or minus, check to see if they = and + are
3070 // right next to each other. If so, the user may have typo'd "x =+ 4"
3071 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003072 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003073 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3074 RHSCheck = ICE->getSubExpr();
3075 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3076 if ((UO->getOpcode() == UnaryOperator::Plus ||
3077 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003078 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003079 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003080 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003081 Diag(Loc, diag::warn_not_compound_assign)
3082 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3083 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003084 }
3085 } else {
3086 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003087 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003088 }
Chris Lattner005ed752008-01-04 18:04:52 +00003089
Chris Lattner1eafdea2008-11-18 01:30:42 +00003090 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3091 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003092 return QualType();
3093
Chris Lattner4b009652007-07-25 00:24:17 +00003094 // C99 6.5.16p3: The type of an assignment expression is the type of the
3095 // left operand unless the left operand has qualified type, in which case
3096 // it is the unqualified version of the type of the left operand.
3097 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3098 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003099 // C++ 5.17p1: the type of the assignment expression is that of its left
3100 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003101 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003102}
3103
Chris Lattner1eafdea2008-11-18 01:30:42 +00003104// C99 6.5.17
3105QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3106 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003107
3108 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003109 DefaultFunctionArrayConversion(RHS);
3110 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003111}
3112
3113/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3114/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003115QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3116 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003117 QualType ResType = Op->getType();
3118 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003119
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003120 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3121 // Decrement of bool is not allowed.
3122 if (!isInc) {
3123 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3124 return QualType();
3125 }
3126 // Increment of bool sets it to true, but is deprecated.
3127 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3128 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003129 // OK!
3130 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3131 // C99 6.5.2.4p2, 6.5.6p2
3132 if (PT->getPointeeType()->isObjectType()) {
3133 // Pointer to object is ok!
3134 } else if (PT->getPointeeType()->isVoidType()) {
3135 // Pointer to void is extension.
3136 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3137 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00003138 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003139 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003140 return QualType();
3141 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003142 } else if (ResType->isComplexType()) {
3143 // C99 does not support ++/-- on complex types, we allow as an extension.
3144 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003145 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003146 } else {
3147 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003148 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003149 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003150 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003151 // At this point, we know we have a real, complex or pointer type.
3152 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003153 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003154 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003155 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003156}
3157
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003158/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003159/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003160/// where the declaration is needed for type checking. We only need to
3161/// handle cases when the expression references a function designator
3162/// or is an lvalue. Here are some examples:
3163/// - &(x) => x
3164/// - &*****f => f for f a function designator.
3165/// - &s.xx => s
3166/// - &s.zz[1].yy -> s, if zz is an array
3167/// - *(x + 1) -> x, if x is an array
3168/// - &"123"[2] -> 0
3169/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003170static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003171 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003172 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003173 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003174 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003175 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003176 // Fields cannot be declared with a 'register' storage class.
3177 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003178 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003179 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003180 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003181 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003182 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003183
Douglas Gregord2baafd2008-10-21 16:13:35 +00003184 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003185 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003186 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003187 return 0;
3188 else
3189 return VD;
3190 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003191 case Stmt::UnaryOperatorClass: {
3192 UnaryOperator *UO = cast<UnaryOperator>(E);
3193
3194 switch(UO->getOpcode()) {
3195 case UnaryOperator::Deref: {
3196 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003197 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3198 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3199 if (!VD || VD->getType()->isPointerType())
3200 return 0;
3201 return VD;
3202 }
3203 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003204 }
3205 case UnaryOperator::Real:
3206 case UnaryOperator::Imag:
3207 case UnaryOperator::Extension:
3208 return getPrimaryDecl(UO->getSubExpr());
3209 default:
3210 return 0;
3211 }
3212 }
3213 case Stmt::BinaryOperatorClass: {
3214 BinaryOperator *BO = cast<BinaryOperator>(E);
3215
3216 // Handle cases involving pointer arithmetic. The result of an
3217 // Assign or AddAssign is not an lvalue so they can be ignored.
3218
3219 // (x + n) or (n + x) => x
3220 if (BO->getOpcode() == BinaryOperator::Add) {
3221 if (BO->getLHS()->getType()->isPointerType()) {
3222 return getPrimaryDecl(BO->getLHS());
3223 } else if (BO->getRHS()->getType()->isPointerType()) {
3224 return getPrimaryDecl(BO->getRHS());
3225 }
3226 }
3227
3228 return 0;
3229 }
Chris Lattner4b009652007-07-25 00:24:17 +00003230 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003231 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003232 case Stmt::ImplicitCastExprClass:
3233 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003234 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003235 default:
3236 return 0;
3237 }
3238}
3239
3240/// CheckAddressOfOperand - The operand of & must be either a function
3241/// designator or an lvalue designating an object. If it is an lvalue, the
3242/// object cannot be declared with storage class register or be a bit field.
3243/// Note: The usual conversions are *not* applied to the operand of the &
3244/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003245/// In C++, the operand might be an overloaded function name, in which case
3246/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003247QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003248 if (op->isTypeDependent())
3249 return Context.DependentTy;
3250
Steve Naroff9c6c3592008-01-13 17:10:08 +00003251 if (getLangOptions().C99) {
3252 // Implement C99-only parts of addressof rules.
3253 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3254 if (uOp->getOpcode() == UnaryOperator::Deref)
3255 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3256 // (assuming the deref expression is valid).
3257 return uOp->getSubExpr()->getType();
3258 }
3259 // Technically, there should be a check for array subscript
3260 // expressions here, but the result of one is always an lvalue anyway.
3261 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003262 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003263 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003264
Chris Lattner4b009652007-07-25 00:24:17 +00003265 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003266 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3267 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003268 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3269 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003270 return QualType();
3271 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003272 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003273 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3274 if (Field->isBitField()) {
3275 Diag(OpLoc, diag::err_typecheck_address_of)
3276 << "bit-field" << op->getSourceRange();
3277 return QualType();
3278 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003279 }
3280 // Check for Apple extension for accessing vector components.
3281 } else if (isa<ArraySubscriptExpr>(op) &&
3282 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003283 Diag(OpLoc, diag::err_typecheck_address_of)
3284 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003285 return QualType();
3286 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003287 // We have an lvalue with a decl. Make sure the decl is not declared
3288 // with the register storage-class specifier.
3289 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3290 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003291 Diag(OpLoc, diag::err_typecheck_address_of)
3292 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003293 return QualType();
3294 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003295 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003296 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003297 } else if (isa<FieldDecl>(dcl)) {
3298 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003299 } else if (isa<FunctionDecl>(dcl)) {
3300 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003301 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003302 else
Chris Lattner4b009652007-07-25 00:24:17 +00003303 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003304 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003305
Chris Lattner4b009652007-07-25 00:24:17 +00003306 // If the operand has type "type", the result has type "pointer to type".
3307 return Context.getPointerType(op->getType());
3308}
3309
Chris Lattnerda5c0872008-11-23 09:13:29 +00003310QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3311 UsualUnaryConversions(Op);
3312 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003313
Chris Lattnerda5c0872008-11-23 09:13:29 +00003314 // Note that per both C89 and C99, this is always legal, even if ptype is an
3315 // incomplete type or void. It would be possible to warn about dereferencing
3316 // a void pointer, but it's completely well-defined, and such a warning is
3317 // unlikely to catch any mistakes.
3318 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003319 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003320
Chris Lattner77d52da2008-11-20 06:06:08 +00003321 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003322 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003323 return QualType();
3324}
3325
3326static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3327 tok::TokenKind Kind) {
3328 BinaryOperator::Opcode Opc;
3329 switch (Kind) {
3330 default: assert(0 && "Unknown binop!");
3331 case tok::star: Opc = BinaryOperator::Mul; break;
3332 case tok::slash: Opc = BinaryOperator::Div; break;
3333 case tok::percent: Opc = BinaryOperator::Rem; break;
3334 case tok::plus: Opc = BinaryOperator::Add; break;
3335 case tok::minus: Opc = BinaryOperator::Sub; break;
3336 case tok::lessless: Opc = BinaryOperator::Shl; break;
3337 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3338 case tok::lessequal: Opc = BinaryOperator::LE; break;
3339 case tok::less: Opc = BinaryOperator::LT; break;
3340 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3341 case tok::greater: Opc = BinaryOperator::GT; break;
3342 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3343 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3344 case tok::amp: Opc = BinaryOperator::And; break;
3345 case tok::caret: Opc = BinaryOperator::Xor; break;
3346 case tok::pipe: Opc = BinaryOperator::Or; break;
3347 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3348 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3349 case tok::equal: Opc = BinaryOperator::Assign; break;
3350 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3351 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3352 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3353 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3354 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3355 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3356 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3357 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3358 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3359 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3360 case tok::comma: Opc = BinaryOperator::Comma; break;
3361 }
3362 return Opc;
3363}
3364
3365static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3366 tok::TokenKind Kind) {
3367 UnaryOperator::Opcode Opc;
3368 switch (Kind) {
3369 default: assert(0 && "Unknown unary op!");
3370 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3371 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3372 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3373 case tok::star: Opc = UnaryOperator::Deref; break;
3374 case tok::plus: Opc = UnaryOperator::Plus; break;
3375 case tok::minus: Opc = UnaryOperator::Minus; break;
3376 case tok::tilde: Opc = UnaryOperator::Not; break;
3377 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003378 case tok::kw___real: Opc = UnaryOperator::Real; break;
3379 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3380 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3381 }
3382 return Opc;
3383}
3384
Douglas Gregord7f915e2008-11-06 23:29:22 +00003385/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3386/// operator @p Opc at location @c TokLoc. This routine only supports
3387/// built-in operations; ActOnBinOp handles overloaded operators.
3388Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3389 unsigned Op,
3390 Expr *lhs, Expr *rhs) {
3391 QualType ResultTy; // Result type of the binary operator.
3392 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3393 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3394
3395 switch (Opc) {
3396 default:
3397 assert(0 && "Unknown binary expr!");
3398 case BinaryOperator::Assign:
3399 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3400 break;
3401 case BinaryOperator::Mul:
3402 case BinaryOperator::Div:
3403 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3404 break;
3405 case BinaryOperator::Rem:
3406 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3407 break;
3408 case BinaryOperator::Add:
3409 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3410 break;
3411 case BinaryOperator::Sub:
3412 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3413 break;
3414 case BinaryOperator::Shl:
3415 case BinaryOperator::Shr:
3416 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3417 break;
3418 case BinaryOperator::LE:
3419 case BinaryOperator::LT:
3420 case BinaryOperator::GE:
3421 case BinaryOperator::GT:
3422 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3423 break;
3424 case BinaryOperator::EQ:
3425 case BinaryOperator::NE:
3426 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3427 break;
3428 case BinaryOperator::And:
3429 case BinaryOperator::Xor:
3430 case BinaryOperator::Or:
3431 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3432 break;
3433 case BinaryOperator::LAnd:
3434 case BinaryOperator::LOr:
3435 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3436 break;
3437 case BinaryOperator::MulAssign:
3438 case BinaryOperator::DivAssign:
3439 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3440 if (!CompTy.isNull())
3441 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3442 break;
3443 case BinaryOperator::RemAssign:
3444 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3445 if (!CompTy.isNull())
3446 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3447 break;
3448 case BinaryOperator::AddAssign:
3449 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3450 if (!CompTy.isNull())
3451 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3452 break;
3453 case BinaryOperator::SubAssign:
3454 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3455 if (!CompTy.isNull())
3456 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3457 break;
3458 case BinaryOperator::ShlAssign:
3459 case BinaryOperator::ShrAssign:
3460 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3461 if (!CompTy.isNull())
3462 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3463 break;
3464 case BinaryOperator::AndAssign:
3465 case BinaryOperator::XorAssign:
3466 case BinaryOperator::OrAssign:
3467 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3468 if (!CompTy.isNull())
3469 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3470 break;
3471 case BinaryOperator::Comma:
3472 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3473 break;
3474 }
3475 if (ResultTy.isNull())
3476 return true;
3477 if (CompTy.isNull())
3478 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3479 else
3480 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3481}
3482
Chris Lattner4b009652007-07-25 00:24:17 +00003483// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003484Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3485 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003486 ExprTy *LHS, ExprTy *RHS) {
3487 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3488 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3489
Steve Naroff87d58b42007-09-16 03:34:24 +00003490 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3491 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003492
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003493 // If either expression is type-dependent, just build the AST.
3494 // FIXME: We'll need to perform some caching of the result of name
3495 // lookup for operator+.
3496 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3497 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3498 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3499 Context.DependentTy, TokLoc);
3500 else
3501 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3502 }
3503
Douglas Gregord7f915e2008-11-06 23:29:22 +00003504 if (getLangOptions().CPlusPlus &&
3505 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3506 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003507 // If this is one of the assignment operators, we only perform
3508 // overload resolution if the left-hand side is a class or
3509 // enumeration type (C++ [expr.ass]p3).
3510 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3511 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3512 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3513 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003514
3515 // Determine which overloaded operator we're dealing with.
3516 static const OverloadedOperatorKind OverOps[] = {
3517 OO_Star, OO_Slash, OO_Percent,
3518 OO_Plus, OO_Minus,
3519 OO_LessLess, OO_GreaterGreater,
3520 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3521 OO_EqualEqual, OO_ExclaimEqual,
3522 OO_Amp,
3523 OO_Caret,
3524 OO_Pipe,
3525 OO_AmpAmp,
3526 OO_PipePipe,
3527 OO_Equal, OO_StarEqual,
3528 OO_SlashEqual, OO_PercentEqual,
3529 OO_PlusEqual, OO_MinusEqual,
3530 OO_LessLessEqual, OO_GreaterGreaterEqual,
3531 OO_AmpEqual, OO_CaretEqual,
3532 OO_PipeEqual,
3533 OO_Comma
3534 };
3535 OverloadedOperatorKind OverOp = OverOps[Opc];
3536
Douglas Gregor5ed15042008-11-18 23:14:02 +00003537 // Add the appropriate overloaded operators (C++ [over.match.oper])
3538 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003539 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003540 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003541 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003542
3543 // Perform overload resolution.
3544 OverloadCandidateSet::iterator Best;
3545 switch (BestViableFunction(CandidateSet, Best)) {
3546 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003547 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003548 FunctionDecl *FnDecl = Best->Function;
3549
Douglas Gregor70d26122008-11-12 17:17:38 +00003550 if (FnDecl) {
3551 // We matched an overloaded operator. Build a call to that
3552 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003553
Douglas Gregor70d26122008-11-12 17:17:38 +00003554 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003555 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3556 if (PerformObjectArgumentInitialization(lhs, Method) ||
3557 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3558 "passing"))
3559 return true;
3560 } else {
3561 // Convert the arguments.
3562 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3563 "passing") ||
3564 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3565 "passing"))
3566 return true;
3567 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003568
Douglas Gregor70d26122008-11-12 17:17:38 +00003569 // Determine the result type
3570 QualType ResultTy
3571 = FnDecl->getType()->getAsFunctionType()->getResultType();
3572 ResultTy = ResultTy.getNonReferenceType();
3573
3574 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003575 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3576 SourceLocation());
3577 UsualUnaryConversions(FnExpr);
3578
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003579 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003580 } else {
3581 // We matched a built-in operator. Convert the arguments, then
3582 // break out so that we will build the appropriate built-in
3583 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003584 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3585 Best->Conversions[0], "passing") ||
3586 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3587 Best->Conversions[1], "passing"))
Douglas Gregor70d26122008-11-12 17:17:38 +00003588 return true;
3589
3590 break;
3591 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003592 }
3593
3594 case OR_No_Viable_Function:
3595 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003596 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003597 break;
3598
3599 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003600 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3601 << BinaryOperator::getOpcodeStr(Opc)
3602 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003603 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3604 return true;
3605 }
3606
Douglas Gregor70d26122008-11-12 17:17:38 +00003607 // Either we found no viable overloaded operator or we matched a
3608 // built-in operator. In either case, fall through to trying to
3609 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003610 }
Chris Lattner4b009652007-07-25 00:24:17 +00003611
Douglas Gregord7f915e2008-11-06 23:29:22 +00003612 // Build a built-in binary operation.
3613 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003614}
3615
3616// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003617Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3618 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003619 Expr *Input = (Expr*)input;
3620 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003621
3622 if (getLangOptions().CPlusPlus &&
3623 (Input->getType()->isRecordType()
3624 || Input->getType()->isEnumeralType())) {
3625 // Determine which overloaded operator we're dealing with.
3626 static const OverloadedOperatorKind OverOps[] = {
3627 OO_None, OO_None,
3628 OO_PlusPlus, OO_MinusMinus,
3629 OO_Amp, OO_Star,
3630 OO_Plus, OO_Minus,
3631 OO_Tilde, OO_Exclaim,
3632 OO_None, OO_None,
3633 OO_None,
3634 OO_None
3635 };
3636 OverloadedOperatorKind OverOp = OverOps[Opc];
3637
3638 // Add the appropriate overloaded operators (C++ [over.match.oper])
3639 // to the candidate set.
3640 OverloadCandidateSet CandidateSet;
3641 if (OverOp != OO_None)
3642 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3643
3644 // Perform overload resolution.
3645 OverloadCandidateSet::iterator Best;
3646 switch (BestViableFunction(CandidateSet, Best)) {
3647 case OR_Success: {
3648 // We found a built-in operator or an overloaded operator.
3649 FunctionDecl *FnDecl = Best->Function;
3650
3651 if (FnDecl) {
3652 // We matched an overloaded operator. Build a call to that
3653 // operator.
3654
3655 // Convert the arguments.
3656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3657 if (PerformObjectArgumentInitialization(Input, Method))
3658 return true;
3659 } else {
3660 // Convert the arguments.
3661 if (PerformCopyInitialization(Input,
3662 FnDecl->getParamDecl(0)->getType(),
3663 "passing"))
3664 return true;
3665 }
3666
3667 // Determine the result type
3668 QualType ResultTy
3669 = FnDecl->getType()->getAsFunctionType()->getResultType();
3670 ResultTy = ResultTy.getNonReferenceType();
3671
3672 // Build the actual expression node.
3673 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3674 SourceLocation());
3675 UsualUnaryConversions(FnExpr);
3676
3677 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3678 } else {
3679 // We matched a built-in operator. Convert the arguments, then
3680 // break out so that we will build the appropriate built-in
3681 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003682 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3683 Best->Conversions[0], "passing"))
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003684 return true;
3685
3686 break;
3687 }
3688 }
3689
3690 case OR_No_Viable_Function:
3691 // No viable function; fall through to handling this as a
3692 // built-in operator, which will produce an error message for us.
3693 break;
3694
3695 case OR_Ambiguous:
3696 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3697 << UnaryOperator::getOpcodeStr(Opc)
3698 << Input->getSourceRange();
3699 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3700 return true;
3701 }
3702
3703 // Either we found no viable overloaded operator or we matched a
3704 // built-in operator. In either case, fall through to trying to
3705 // build a built-in operation.
3706 }
3707
Chris Lattner4b009652007-07-25 00:24:17 +00003708 QualType resultType;
3709 switch (Opc) {
3710 default:
3711 assert(0 && "Unimplemented unary expr!");
3712 case UnaryOperator::PreInc:
3713 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003714 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3715 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003716 break;
3717 case UnaryOperator::AddrOf:
3718 resultType = CheckAddressOfOperand(Input, OpLoc);
3719 break;
3720 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003721 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003722 resultType = CheckIndirectionOperand(Input, OpLoc);
3723 break;
3724 case UnaryOperator::Plus:
3725 case UnaryOperator::Minus:
3726 UsualUnaryConversions(Input);
3727 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003728 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3729 break;
3730 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3731 resultType->isEnumeralType())
3732 break;
3733 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3734 Opc == UnaryOperator::Plus &&
3735 resultType->isPointerType())
3736 break;
3737
Chris Lattner77d52da2008-11-20 06:06:08 +00003738 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003739 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003740 case UnaryOperator::Not: // bitwise complement
3741 UsualUnaryConversions(Input);
3742 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003743 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3744 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3745 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003746 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003747 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003748 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003749 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003750 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003751 break;
3752 case UnaryOperator::LNot: // logical negation
3753 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3754 DefaultFunctionArrayConversion(Input);
3755 resultType = Input->getType();
3756 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003757 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003758 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003759 // LNot always has type int. C99 6.5.3.3p5.
3760 resultType = Context.IntTy;
3761 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003762 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003763 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003764 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003765 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003766 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003767 resultType = Input->getType();
3768 break;
3769 }
3770 if (resultType.isNull())
3771 return true;
3772 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3773}
3774
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003775/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3776Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003777 SourceLocation LabLoc,
3778 IdentifierInfo *LabelII) {
3779 // Look up the record for this label identifier.
3780 LabelStmt *&LabelDecl = LabelMap[LabelII];
3781
Daniel Dunbar879788d2008-08-04 16:51:22 +00003782 // If we haven't seen this label yet, create a forward reference. It
3783 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003784 if (LabelDecl == 0)
3785 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3786
3787 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003788 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3789 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003790}
3791
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003792Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003793 SourceLocation RPLoc) { // "({..})"
3794 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3795 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3796 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3797
3798 // FIXME: there are a variety of strange constraints to enforce here, for
3799 // example, it is not possible to goto into a stmt expression apparently.
3800 // More semantic analysis is needed.
3801
3802 // FIXME: the last statement in the compount stmt has its value used. We
3803 // should not warn about it being unused.
3804
3805 // If there are sub stmts in the compound stmt, take the type of the last one
3806 // as the type of the stmtexpr.
3807 QualType Ty = Context.VoidTy;
3808
Chris Lattner200964f2008-07-26 19:51:01 +00003809 if (!Compound->body_empty()) {
3810 Stmt *LastStmt = Compound->body_back();
3811 // If LastStmt is a label, skip down through into the body.
3812 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3813 LastStmt = Label->getSubStmt();
3814
3815 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003816 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003817 }
Chris Lattner4b009652007-07-25 00:24:17 +00003818
3819 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3820}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003821
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003822Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3823 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003824 SourceLocation TypeLoc,
3825 TypeTy *argty,
3826 OffsetOfComponent *CompPtr,
3827 unsigned NumComponents,
3828 SourceLocation RPLoc) {
3829 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3830 assert(!ArgTy.isNull() && "Missing type argument!");
3831
3832 // We must have at least one component that refers to the type, and the first
3833 // one is known to be a field designator. Verify that the ArgTy represents
3834 // a struct/union/class.
3835 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003836 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003837
3838 // Otherwise, create a compound literal expression as the base, and
3839 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003840 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003841
Chris Lattnerb37522e2007-08-31 21:49:13 +00003842 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3843 // GCC extension, diagnose them.
3844 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003845 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3846 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003847
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003848 for (unsigned i = 0; i != NumComponents; ++i) {
3849 const OffsetOfComponent &OC = CompPtr[i];
3850 if (OC.isBrackets) {
3851 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003852 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003853 if (!AT) {
3854 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003855 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003856 }
3857
Chris Lattner2af6a802007-08-30 17:59:59 +00003858 // FIXME: C++: Verify that operator[] isn't overloaded.
3859
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003860 // C99 6.5.2.1p1
3861 Expr *Idx = static_cast<Expr*>(OC.U.E);
3862 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003863 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3864 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003865
3866 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3867 continue;
3868 }
3869
3870 const RecordType *RC = Res->getType()->getAsRecordType();
3871 if (!RC) {
3872 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003873 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003874 }
3875
3876 // Get the decl corresponding to this.
3877 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003878 FieldDecl *MemberDecl
3879 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3880 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00003881 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003882 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003883 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3884 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003885
3886 // FIXME: C++: Verify that MemberDecl isn't a static field.
3887 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003888 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3889 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003890 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3891 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003892 }
3893
3894 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3895 BuiltinLoc);
3896}
3897
3898
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003899Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003900 TypeTy *arg1, TypeTy *arg2,
3901 SourceLocation RPLoc) {
3902 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3903 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3904
3905 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3906
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003907 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003908}
3909
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003910Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003911 ExprTy *expr1, ExprTy *expr2,
3912 SourceLocation RPLoc) {
3913 Expr *CondExpr = static_cast<Expr*>(cond);
3914 Expr *LHSExpr = static_cast<Expr*>(expr1);
3915 Expr *RHSExpr = static_cast<Expr*>(expr2);
3916
3917 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3918
3919 // The conditional expression is required to be a constant expression.
3920 llvm::APSInt condEval(32);
3921 SourceLocation ExpLoc;
3922 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003923 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3924 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003925
3926 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3927 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3928 RHSExpr->getType();
3929 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3930}
3931
Steve Naroff52a81c02008-09-03 18:15:37 +00003932//===----------------------------------------------------------------------===//
3933// Clang Extensions.
3934//===----------------------------------------------------------------------===//
3935
3936/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003937void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003938 // Analyze block parameters.
3939 BlockSemaInfo *BSI = new BlockSemaInfo();
3940
3941 // Add BSI to CurBlock.
3942 BSI->PrevBlockInfo = CurBlock;
3943 CurBlock = BSI;
3944
3945 BSI->ReturnType = 0;
3946 BSI->TheScope = BlockScope;
3947
Steve Naroff52059382008-10-10 01:28:17 +00003948 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003949 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003950}
3951
3952void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003953 // Analyze arguments to block.
3954 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3955 "Not a function declarator!");
3956 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3957
Steve Naroff52059382008-10-10 01:28:17 +00003958 CurBlock->hasPrototype = FTI.hasPrototype;
3959 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003960
3961 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3962 // no arguments, not a function that takes a single void argument.
3963 if (FTI.hasPrototype &&
3964 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3965 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3966 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3967 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003968 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003969 } else if (FTI.hasPrototype) {
3970 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003971 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3972 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003973 }
Steve Naroff52059382008-10-10 01:28:17 +00003974 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3975
3976 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3977 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3978 // If this has an identifier, add it to the scope stack.
3979 if ((*AI)->getIdentifier())
3980 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003981}
3982
3983/// ActOnBlockError - If there is an error parsing a block, this callback
3984/// is invoked to pop the information about the block from the action impl.
3985void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3986 // Ensure that CurBlock is deleted.
3987 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3988
3989 // Pop off CurBlock, handle nested blocks.
3990 CurBlock = CurBlock->PrevBlockInfo;
3991
3992 // FIXME: Delete the ParmVarDecl objects as well???
3993
3994}
3995
3996/// ActOnBlockStmtExpr - This is called when the body of a block statement
3997/// literal was successfully completed. ^(int x){...}
3998Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3999 Scope *CurScope) {
4000 // Ensure that CurBlock is deleted.
4001 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4002 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4003
Steve Naroff52059382008-10-10 01:28:17 +00004004 PopDeclContext();
4005
Steve Naroff52a81c02008-09-03 18:15:37 +00004006 // Pop off CurBlock, handle nested blocks.
4007 CurBlock = CurBlock->PrevBlockInfo;
4008
4009 QualType RetTy = Context.VoidTy;
4010 if (BSI->ReturnType)
4011 RetTy = QualType(BSI->ReturnType, 0);
4012
4013 llvm::SmallVector<QualType, 8> ArgTypes;
4014 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4015 ArgTypes.push_back(BSI->Params[i]->getType());
4016
4017 QualType BlockTy;
4018 if (!BSI->hasPrototype)
4019 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4020 else
4021 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004022 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004023
4024 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004025
Steve Naroff95029d92008-10-08 18:44:00 +00004026 BSI->TheDecl->setBody(Body.take());
4027 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004028}
4029
Nate Begemanbd881ef2008-01-30 20:50:20 +00004030/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004031/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004032/// The number of arguments has already been validated to match the number of
4033/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004034static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4035 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004036 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004037 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004038 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4039 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004040
4041 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004042 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004043 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004044 return true;
4045}
4046
4047Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4048 SourceLocation *CommaLocs,
4049 SourceLocation BuiltinLoc,
4050 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004051 // __builtin_overload requires at least 2 arguments
4052 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004053 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4054 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004055
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004056 // The first argument is required to be a constant expression. It tells us
4057 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004058 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004059 Expr *NParamsExpr = Args[0];
4060 llvm::APSInt constEval(32);
4061 SourceLocation ExpLoc;
4062 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004063 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4064 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004065
4066 // Verify that the number of parameters is > 0
4067 unsigned NumParams = constEval.getZExtValue();
4068 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004069 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4070 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004071 // Verify that we have at least 1 + NumParams arguments to the builtin.
4072 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004073 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4074 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004075
4076 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004077 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004078 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004079 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4080 // UsualUnaryConversions will convert the function DeclRefExpr into a
4081 // pointer to function.
4082 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004083 const FunctionTypeProto *FnType = 0;
4084 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4085 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004086
4087 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4088 // parameters, and the number of parameters must match the value passed to
4089 // the builtin.
4090 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004091 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4092 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004093
4094 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004095 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004096 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004097 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004098 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004099 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4100 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004101 // Remember our match, and continue processing the remaining arguments
4102 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004103 OE = new OverloadExpr(Args, NumArgs, i,
4104 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004105 BuiltinLoc, RParenLoc);
4106 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004107 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004108 // Return the newly created OverloadExpr node, if we succeded in matching
4109 // exactly one of the candidate functions.
4110 if (OE)
4111 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004112
4113 // If we didn't find a matching function Expr in the __builtin_overload list
4114 // the return an error.
4115 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004116 for (unsigned i = 0; i != NumParams; ++i) {
4117 if (i != 0) typeNames += ", ";
4118 typeNames += Args[i+1]->getType().getAsString();
4119 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004120
Chris Lattner77d52da2008-11-20 06:06:08 +00004121 return Diag(BuiltinLoc, diag::err_overload_no_match)
4122 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004123}
4124
Anders Carlsson36760332007-10-15 20:28:48 +00004125Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4126 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004127 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004128 Expr *E = static_cast<Expr*>(expr);
4129 QualType T = QualType::getFromOpaquePtr(type);
4130
4131 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004132
4133 // Get the va_list type
4134 QualType VaListType = Context.getBuiltinVaListType();
4135 // Deal with implicit array decay; for example, on x86-64,
4136 // va_list is an array, but it's supposed to decay to
4137 // a pointer for va_arg.
4138 if (VaListType->isArrayType())
4139 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004140 // Make sure the input expression also decays appropriately.
4141 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004142
4143 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004144 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004145 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004146 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004147
4148 // FIXME: Warn if a non-POD type is passed in.
4149
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004150 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004151}
4152
Douglas Gregorad4b3792008-11-29 04:51:27 +00004153Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4154 // The type of __null will be int or long, depending on the size of
4155 // pointers on the target.
4156 QualType Ty;
4157 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4158 Ty = Context.IntTy;
4159 else
4160 Ty = Context.LongTy;
4161
4162 return new GNUNullExpr(Ty, TokenLoc);
4163}
4164
Chris Lattner005ed752008-01-04 18:04:52 +00004165bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4166 SourceLocation Loc,
4167 QualType DstType, QualType SrcType,
4168 Expr *SrcExpr, const char *Flavor) {
4169 // Decode the result (notice that AST's are still created for extensions).
4170 bool isInvalid = false;
4171 unsigned DiagKind;
4172 switch (ConvTy) {
4173 default: assert(0 && "Unknown conversion type");
4174 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004175 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004176 DiagKind = diag::ext_typecheck_convert_pointer_int;
4177 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004178 case IntToPointer:
4179 DiagKind = diag::ext_typecheck_convert_int_pointer;
4180 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004181 case IncompatiblePointer:
4182 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4183 break;
4184 case FunctionVoidPointer:
4185 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4186 break;
4187 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004188 // If the qualifiers lost were because we were applying the
4189 // (deprecated) C++ conversion from a string literal to a char*
4190 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4191 // Ideally, this check would be performed in
4192 // CheckPointerTypesForAssignment. However, that would require a
4193 // bit of refactoring (so that the second argument is an
4194 // expression, rather than a type), which should be done as part
4195 // of a larger effort to fix CheckPointerTypesForAssignment for
4196 // C++ semantics.
4197 if (getLangOptions().CPlusPlus &&
4198 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4199 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004200 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4201 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004202 case IntToBlockPointer:
4203 DiagKind = diag::err_int_to_block_pointer;
4204 break;
4205 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004206 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004207 break;
Steve Naroff19608432008-10-14 22:18:38 +00004208 case IncompatibleObjCQualifiedId:
4209 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4210 // it can give a more specific diagnostic.
4211 DiagKind = diag::warn_incompatible_qualified_id;
4212 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004213 case Incompatible:
4214 DiagKind = diag::err_typecheck_convert_incompatible;
4215 isInvalid = true;
4216 break;
4217 }
4218
Chris Lattner271d4c22008-11-24 05:29:24 +00004219 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4220 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004221 return isInvalid;
4222}
Anders Carlssond5201b92008-11-30 19:50:32 +00004223
4224bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4225{
4226 Expr::EvalResult EvalResult;
4227
4228 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4229 EvalResult.HasSideEffects) {
4230 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4231
4232 if (EvalResult.Diag) {
4233 // We only show the note if it's not the usual "invalid subexpression"
4234 // or if it's actually in a subexpression.
4235 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4236 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4237 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4238 }
4239
4240 return true;
4241 }
4242
4243 if (EvalResult.Diag) {
4244 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4245 E->getSourceRange();
4246
4247 // Print the reason it's not a constant.
4248 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4249 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4250 }
4251
4252 if (Result)
4253 *Result = EvalResult.Val.getInt();
4254 return false;
4255}