blob: 49bba1d5b81b1f9db27ce62bc347b7c24f3a5ad3 [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"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#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 Lattner2cb744b2009-02-15 22:43:40 +000029
30/// DiagnoseUseOfDeprecatedDeclImpl - If the specified decl is deprecated or
31// unavailable, emit the corresponding diagnostics.
32void Sema::DiagnoseUseOfDeprecatedDeclImpl(NamedDecl *D, SourceLocation Loc) {
33 // See if the decl is deprecated.
34 if (D->getAttr<DeprecatedAttr>()) {
35 // If this reference happens *in* a deprecated function or method, don't
36 // warn. Implementing deprecated stuff requires referencing depreated
37 // stuff.
38 NamedDecl *ND = getCurFunctionOrMethodDecl();
39 if (ND == 0 || !ND->getAttr<DeprecatedAttr>())
40 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
41 }
42
43 // See if hte decl is unavailable.
44 if (D->getAttr<UnavailableAttr>())
45 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
46}
47
Chris Lattner299b8842008-07-25 21:10:04 +000048//===----------------------------------------------------------------------===//
49// Standard Promotions and Conversions
50//===----------------------------------------------------------------------===//
51
Chris Lattner299b8842008-07-25 21:10:04 +000052/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
53void Sema::DefaultFunctionArrayConversion(Expr *&E) {
54 QualType Ty = E->getType();
55 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
56
Chris Lattner299b8842008-07-25 21:10:04 +000057 if (Ty->isFunctionType())
58 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000059 else if (Ty->isArrayType()) {
60 // In C90 mode, arrays only promote to pointers if the array expression is
61 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
62 // type 'array of type' is converted to an expression that has type 'pointer
63 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
64 // that has type 'array of type' ...". The relevant change is "an lvalue"
65 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000066 //
67 // C++ 4.2p1:
68 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
69 // T" can be converted to an rvalue of type "pointer to T".
70 //
71 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
72 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000073 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
74 }
Chris Lattner299b8842008-07-25 21:10:04 +000075}
76
77/// UsualUnaryConversions - Performs various conversions that are common to most
78/// operators (C99 6.3). The conversions of array and function types are
79/// sometimes surpressed. For example, the array->pointer conversion doesn't
80/// apply if the array is an argument to the sizeof or address (&) operators.
81/// In these instances, this routine should *not* be called.
82Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
83 QualType Ty = Expr->getType();
84 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
85
Chris Lattner299b8842008-07-25 21:10:04 +000086 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
87 ImpCastExprToType(Expr, Context.IntTy);
88 else
89 DefaultFunctionArrayConversion(Expr);
90
91 return Expr;
92}
93
Chris Lattner9305c3d2008-07-25 22:25:12 +000094/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
95/// do not have a prototype. Arguments that have type float are promoted to
96/// double. All other argument types are converted by UsualUnaryConversions().
97void Sema::DefaultArgumentPromotion(Expr *&Expr) {
98 QualType Ty = Expr->getType();
99 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
100
101 // If this is a 'float' (CVR qualified or typedef) promote to double.
102 if (const BuiltinType *BT = Ty->getAsBuiltinType())
103 if (BT->getKind() == BuiltinType::Float)
104 return ImpCastExprToType(Expr, Context.DoubleTy);
105
106 UsualUnaryConversions(Expr);
107}
108
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000109// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
110// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000111void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000112 DefaultArgumentPromotion(Expr);
113
114 if (!Expr->getType()->isPODType()) {
115 Diag(Expr->getLocStart(),
116 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
117 Expr->getType() << CT;
118 }
119}
120
121
Chris Lattner299b8842008-07-25 21:10:04 +0000122/// UsualArithmeticConversions - Performs various conversions that are common to
123/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
124/// routine returns the first non-arithmetic type found. The client is
125/// responsible for emitting appropriate error diagnostics.
126/// FIXME: verify the conversion rules for "complex int" are consistent with
127/// GCC.
128QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
129 bool isCompAssign) {
130 if (!isCompAssign) {
131 UsualUnaryConversions(lhsExpr);
132 UsualUnaryConversions(rhsExpr);
133 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000134
Chris Lattner299b8842008-07-25 21:10:04 +0000135 // For conversion purposes, we ignore any qualifiers.
136 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000137 QualType lhs =
138 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
139 QualType rhs =
140 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000141
142 // If both types are identical, no conversion is needed.
143 if (lhs == rhs)
144 return lhs;
145
146 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
147 // The caller can deal with this (e.g. pointer + int).
148 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
149 return lhs;
150
151 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
152 if (!isCompAssign) {
153 ImpCastExprToType(lhsExpr, destType);
154 ImpCastExprToType(rhsExpr, destType);
155 }
156 return destType;
157}
158
159QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
160 // Perform the usual unary conversions. We do this early so that
161 // integral promotions to "int" can allow us to exit early, in the
162 // lhs == rhs check. Also, for conversion purposes, we ignore any
163 // qualifiers. For example, "const float" and "float" are
164 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000165 if (lhs->isPromotableIntegerType())
166 lhs = Context.IntTy;
167 else
168 lhs = lhs.getUnqualifiedType();
169 if (rhs->isPromotableIntegerType())
170 rhs = Context.IntTy;
171 else
172 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000173
Chris Lattner299b8842008-07-25 21:10:04 +0000174 // If both types are identical, no conversion is needed.
175 if (lhs == rhs)
176 return lhs;
177
178 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
179 // The caller can deal with this (e.g. pointer + int).
180 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
181 return lhs;
182
183 // At this point, we have two different arithmetic types.
184
185 // Handle complex types first (C99 6.3.1.8p1).
186 if (lhs->isComplexType() || rhs->isComplexType()) {
187 // if we have an integer operand, the result is the complex type.
188 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
189 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000190 return lhs;
191 }
192 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
193 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return rhs;
195 }
196 // This handles complex/complex, complex/float, or float/complex.
197 // When both operands are complex, the shorter operand is converted to the
198 // type of the longer, and that is the type of the result. This corresponds
199 // to what is done when combining two real floating-point operands.
200 // The fun begins when size promotion occur across type domains.
201 // From H&S 6.3.4: When one operand is complex and the other is a real
202 // floating-point type, the less precise type is converted, within it's
203 // real or complex domain, to the precision of the other type. For example,
204 // when combining a "long double" with a "double _Complex", the
205 // "double _Complex" is promoted to "long double _Complex".
206 int result = Context.getFloatingTypeOrder(lhs, rhs);
207
208 if (result > 0) { // The left side is bigger, convert rhs.
209 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000210 } else if (result < 0) { // The right side is bigger, convert lhs.
211 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000212 }
213 // At this point, lhs and rhs have the same rank/size. Now, make sure the
214 // domains match. This is a requirement for our implementation, C99
215 // does not require this promotion.
216 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
217 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000218 return rhs;
219 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000220 return lhs;
221 }
222 }
223 return lhs; // The domain/size match exactly.
224 }
225 // Now handle "real" floating types (i.e. float, double, long double).
226 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
227 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000228 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000229 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000230 return lhs;
231 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000232 if (rhs->isComplexIntegerType()) {
233 // convert rhs to the complex floating point type.
234 return Context.getComplexType(lhs);
235 }
236 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000237 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000238 return rhs;
239 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000240 if (lhs->isComplexIntegerType()) {
241 // convert lhs to the complex floating point type.
242 return Context.getComplexType(rhs);
243 }
Chris Lattner299b8842008-07-25 21:10:04 +0000244 // We have two real floating types, float/complex combos were handled above.
245 // Convert the smaller operand to the bigger result.
246 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000247 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000248 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000249 assert(result < 0 && "illegal float comparison");
250 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000251 }
252 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
253 // Handle GCC complex int extension.
254 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
255 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
256
257 if (lhsComplexInt && rhsComplexInt) {
258 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000259 rhsComplexInt->getElementType()) >= 0)
260 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000261 return rhs;
262 } else if (lhsComplexInt && rhs->isIntegerType()) {
263 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000264 return lhs;
265 } else if (rhsComplexInt && lhs->isIntegerType()) {
266 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return rhs;
268 }
269 }
270 // Finally, we have two differing integer types.
271 // The rules for this case are in C99 6.3.1.8
272 int compare = Context.getIntegerTypeOrder(lhs, rhs);
273 bool lhsSigned = lhs->isSignedIntegerType(),
274 rhsSigned = rhs->isSignedIntegerType();
275 QualType destType;
276 if (lhsSigned == rhsSigned) {
277 // Same signedness; use the higher-ranked type
278 destType = compare >= 0 ? lhs : rhs;
279 } else if (compare != (lhsSigned ? 1 : -1)) {
280 // The unsigned type has greater than or equal rank to the
281 // signed type, so use the unsigned type
282 destType = lhsSigned ? rhs : lhs;
283 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
284 // The two types are different widths; if we are here, that
285 // means the signed type is larger than the unsigned type, so
286 // use the signed type.
287 destType = lhsSigned ? lhs : rhs;
288 } else {
289 // The signed type is higher-ranked than the unsigned type,
290 // but isn't actually any bigger (like unsigned int and long
291 // on most 32-bit systems). Use the unsigned type corresponding
292 // to the signed type.
293 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
294 }
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return destType;
296}
297
298//===----------------------------------------------------------------------===//
299// Semantic Analysis for various Expression Types
300//===----------------------------------------------------------------------===//
301
302
Steve Naroff87d58b42007-09-16 03:34:24 +0000303/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
305/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
306/// multiple tokens. However, the common case is that StringToks points to one
307/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000308///
309Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000310Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000311 assert(NumStringToks && "Must have at least one string!");
312
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000313 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000314 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000315 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000316
317 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
318 for (unsigned i = 0; i != NumStringToks; ++i)
319 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000320
Chris Lattnera6dcce32008-02-11 00:02:17 +0000321 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000322 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000323 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000324
325 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
326 if (getLangOptions().CPlusPlus)
327 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000328
Chris Lattnera6dcce32008-02-11 00:02:17 +0000329 // Get an array type for the string, according to C99 6.4.5. This includes
330 // the nul terminator character as well as the string length for pascal
331 // strings.
332 StrTy = Context.getConstantArrayType(StrTy,
333 llvm::APInt(32, Literal.GetStringLength()+1),
334 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000335
Chris Lattner4b009652007-07-25 00:24:17 +0000336 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000337 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000338 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000339 Literal.AnyWide, StrTy,
340 StringToks[0].getLocation(),
341 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000342}
343
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000344/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
345/// CurBlock to VD should cause it to be snapshotted (as we do for auto
346/// variables defined outside the block) or false if this is not needed (e.g.
347/// for values inside the block or for globals).
348///
349/// FIXME: This will create BlockDeclRefExprs for global variables,
350/// function references, etc which is suboptimal :) and breaks
351/// things like "integer constant expression" tests.
352static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
353 ValueDecl *VD) {
354 // If the value is defined inside the block, we couldn't snapshot it even if
355 // we wanted to.
356 if (CurBlock->TheDecl == VD->getDeclContext())
357 return false;
358
359 // If this is an enum constant or function, it is constant, don't snapshot.
360 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
361 return false;
362
363 // If this is a reference to an extern, static, or global variable, no need to
364 // snapshot it.
365 // FIXME: What about 'const' variables in C++?
366 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
367 return Var->hasLocalStorage();
368
369 return true;
370}
371
372
373
Steve Naroff0acc9c92007-09-15 18:49:24 +0000374/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000375/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000376/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000377/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000378/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000379Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
380 IdentifierInfo &II,
381 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000382 const CXXScopeSpec *SS,
383 bool isAddressOfOperand) {
384 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000385 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000386}
387
Douglas Gregor566782a2009-01-06 05:10:23 +0000388/// BuildDeclRefExpr - Build either a DeclRefExpr or a
389/// QualifiedDeclRefExpr based on whether or not SS is a
390/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000391DeclRefExpr *
392Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
393 bool TypeDependent, bool ValueDependent,
394 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000395 if (SS && !SS->isEmpty())
396 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000397 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000398 else
399 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000400}
401
Douglas Gregor723d3332009-01-07 00:43:41 +0000402/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
403/// variable corresponding to the anonymous union or struct whose type
404/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000405static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000406 assert(Record->isAnonymousStructOrUnion() &&
407 "Record must be an anonymous struct or union!");
408
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000409 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000410 // be an O(1) operation rather than a slow walk through DeclContext's
411 // vector (which itself will be eliminated). DeclGroups might make
412 // this even better.
413 DeclContext *Ctx = Record->getDeclContext();
414 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
415 DEnd = Ctx->decls_end();
416 D != DEnd; ++D) {
417 if (*D == Record) {
418 // The object for the anonymous struct/union directly
419 // follows its type in the list of declarations.
420 ++D;
421 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000422 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000423 return *D;
424 }
425 }
426
427 assert(false && "Missing object for anonymous record");
428 return 0;
429}
430
Sebastian Redlcd883f72009-01-18 18:53:16 +0000431Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000432Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
433 FieldDecl *Field,
434 Expr *BaseObjectExpr,
435 SourceLocation OpLoc) {
436 assert(Field->getDeclContext()->isRecord() &&
437 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
438 && "Field must be stored inside an anonymous struct or union");
439
440 // Construct the sequence of field member references
441 // we'll have to perform to get to the field in the anonymous
442 // union/struct. The list of members is built from the field
443 // outward, so traverse it backwards to go from an object in
444 // the current context to the field we found.
445 llvm::SmallVector<FieldDecl *, 4> AnonFields;
446 AnonFields.push_back(Field);
447 VarDecl *BaseObject = 0;
448 DeclContext *Ctx = Field->getDeclContext();
449 do {
450 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000451 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000452 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
453 AnonFields.push_back(AnonField);
454 else {
455 BaseObject = cast<VarDecl>(AnonObject);
456 break;
457 }
458 Ctx = Ctx->getParent();
459 } while (Ctx->isRecord() &&
460 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
461
462 // Build the expression that refers to the base object, from
463 // which we will build a sequence of member references to each
464 // of the anonymous union objects and, eventually, the field we
465 // found via name lookup.
466 bool BaseObjectIsPointer = false;
467 unsigned ExtraQuals = 0;
468 if (BaseObject) {
469 // BaseObject is an anonymous struct/union variable (and is,
470 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000471 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000472 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000473 SourceLocation());
474 ExtraQuals
475 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
476 } else if (BaseObjectExpr) {
477 // The caller provided the base object expression. Determine
478 // whether its a pointer and whether it adds any qualifiers to the
479 // anonymous struct/union fields we're looking into.
480 QualType ObjectType = BaseObjectExpr->getType();
481 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
482 BaseObjectIsPointer = true;
483 ObjectType = ObjectPtr->getPointeeType();
484 }
485 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
486 } else {
487 // We've found a member of an anonymous struct/union that is
488 // inside a non-anonymous struct/union, so in a well-formed
489 // program our base object expression is "this".
490 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
491 if (!MD->isStatic()) {
492 QualType AnonFieldType
493 = Context.getTagDeclType(
494 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
495 QualType ThisType = Context.getTagDeclType(MD->getParent());
496 if ((Context.getCanonicalType(AnonFieldType)
497 == Context.getCanonicalType(ThisType)) ||
498 IsDerivedFrom(ThisType, AnonFieldType)) {
499 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000500 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000501 MD->getThisType(Context));
502 BaseObjectIsPointer = true;
503 }
504 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000505 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
506 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000507 }
508 ExtraQuals = MD->getTypeQualifiers();
509 }
510
511 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000512 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
513 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000514 }
515
516 // Build the implicit member references to the field of the
517 // anonymous struct/union.
518 Expr *Result = BaseObjectExpr;
519 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
520 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
521 FI != FIEnd; ++FI) {
522 QualType MemberType = (*FI)->getType();
523 if (!(*FI)->isMutable()) {
524 unsigned combinedQualifiers
525 = MemberType.getCVRQualifiers() | ExtraQuals;
526 MemberType = MemberType.getQualifiedType(combinedQualifiers);
527 }
Steve Naroff774e4152009-01-21 00:14:39 +0000528 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
529 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000530 BaseObjectIsPointer = false;
531 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
532 OpLoc = SourceLocation();
533 }
534
Sebastian Redlcd883f72009-01-18 18:53:16 +0000535 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000536}
537
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000538/// ActOnDeclarationNameExpr - The parser has read some kind of name
539/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
540/// performs lookup on that name and returns an expression that refers
541/// to that name. This routine isn't directly called from the parser,
542/// because the parser doesn't know about DeclarationName. Rather,
543/// this routine is called by ActOnIdentifierExpr,
544/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
545/// which form the DeclarationName from the corresponding syntactic
546/// forms.
547///
548/// HasTrailingLParen indicates whether this identifier is used in a
549/// function call context. LookupCtx is only used for a C++
550/// qualified-id (foo::bar) to indicate the class or namespace that
551/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000552///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000553/// isAddressOfOperand means that this expression is the direct operand
554/// of an address-of operator. This matters because this is the only
555/// situation where a qualified name referencing a non-static member may
556/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000557Sema::OwningExprResult
558Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
559 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000560 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000561 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000562 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000563 if (SS && SS->isInvalid())
564 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000565 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
566 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000567
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000568 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
569 HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
570 // We've seen something of the form
571 //
572 // identifier(
573 //
574 // and we did not find any entity by the name
575 // "identifier". However, this identifier is still subject to
576 // argument-dependent lookup, so keep track of the name.
577 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
578 Context.OverloadTy,
579 Loc));
580 }
581
Douglas Gregor09be81b2009-02-04 17:27:36 +0000582 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000583 if (Lookup.isAmbiguous()) {
584 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
585 SS && SS->isSet() ? SS->getRange()
586 : SourceRange());
587 return ExprError();
588 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000589 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000590
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000591 // If this reference is in an Objective-C method, then ivar lookup happens as
592 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000593 IdentifierInfo *II = Name.getAsIdentifierInfo();
594 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000595 // There are two cases to handle here. 1) scoped lookup could have failed,
596 // in which case we should look for an ivar. 2) scoped lookup could have
597 // found a decl, but that decl is outside the current method (i.e. a global
598 // variable). In these two cases, we do a lookup for an ivar with this
599 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000600 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000601 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000602 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000603 // Check if referencing a field with __attribute__((deprecated)).
604 DiagnoseUseOfDeprecatedDecl(IV, Loc);
605
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000606 // FIXME: This should use a new expr for a direct reference, don't turn
607 // this into Self->ivar, just return a BareIVarExpr or something.
608 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000610 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
611 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000612 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000613 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000614 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000615 }
616 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000617 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000618 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000619 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000620 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000621 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000622 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000623 }
Chris Lattner4b009652007-07-25 00:24:17 +0000624 if (D == 0) {
625 // Otherwise, this could be an implicitly declared function reference (legal
626 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000627 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000628 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000629 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000630 else {
631 // If this name wasn't predeclared and if this is not a function call,
632 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000633 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000634 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
635 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000636 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
637 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000638 return ExprError(Diag(Loc, diag::err_undeclared_use)
639 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000640 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000641 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000642 }
643 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000644
Sebastian Redl0c9da212009-02-03 20:19:35 +0000645 // If this is an expression of the form &Class::member, don't build an
646 // implicit member ref, because we want a pointer to the member in general,
647 // not any specific instance's member.
648 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000649 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000650 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000651 QualType DType;
652 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
653 DType = FD->getType().getNonReferenceType();
654 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
655 DType = Method->getType();
656 } else if (isa<OverloadedFunctionDecl>(D)) {
657 DType = Context.OverloadTy;
658 }
659 // Could be an inner type. That's diagnosed below, so ignore it here.
660 if (!DType.isNull()) {
661 // The pointer is type- and value-dependent if it points into something
662 // dependent.
663 bool Dependent = false;
664 for (; DC; DC = DC->getParent()) {
665 // FIXME: could stop early at namespace scope.
666 if (DC->isRecord()) {
667 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
668 if (Context.getTypeDeclType(Record)->isDependentType()) {
669 Dependent = true;
670 break;
671 }
672 }
673 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000674 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000675 }
676 }
677 }
678
Douglas Gregor723d3332009-01-07 00:43:41 +0000679 // We may have found a field within an anonymous union or struct
680 // (C++ [class.union]).
681 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
682 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
683 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000684
Douglas Gregor3257fb52008-12-22 05:46:06 +0000685 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
686 if (!MD->isStatic()) {
687 // C++ [class.mfct.nonstatic]p2:
688 // [...] if name lookup (3.4.1) resolves the name in the
689 // id-expression to a nonstatic nontype member of class X or of
690 // a base class of X, the id-expression is transformed into a
691 // class member access expression (5.2.5) using (*this) (9.3.2)
692 // as the postfix-expression to the left of the '.' operator.
693 DeclContext *Ctx = 0;
694 QualType MemberType;
695 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
696 Ctx = FD->getDeclContext();
697 MemberType = FD->getType();
698
699 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
700 MemberType = RefType->getPointeeType();
701 else if (!FD->isMutable()) {
702 unsigned combinedQualifiers
703 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
704 MemberType = MemberType.getQualifiedType(combinedQualifiers);
705 }
706 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
707 if (!Method->isStatic()) {
708 Ctx = Method->getParent();
709 MemberType = Method->getType();
710 }
711 } else if (OverloadedFunctionDecl *Ovl
712 = dyn_cast<OverloadedFunctionDecl>(D)) {
713 for (OverloadedFunctionDecl::function_iterator
714 Func = Ovl->function_begin(),
715 FuncEnd = Ovl->function_end();
716 Func != FuncEnd; ++Func) {
717 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
718 if (!DMethod->isStatic()) {
719 Ctx = Ovl->getDeclContext();
720 MemberType = Context.OverloadTy;
721 break;
722 }
723 }
724 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000725
726 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000727 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
728 QualType ThisType = Context.getTagDeclType(MD->getParent());
729 if ((Context.getCanonicalType(CtxType)
730 == Context.getCanonicalType(ThisType)) ||
731 IsDerivedFrom(ThisType, CtxType)) {
732 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000733 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000734 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000735 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000736 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000737 }
738 }
739 }
740 }
741
Douglas Gregor8acb7272008-12-11 16:49:14 +0000742 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000743 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
744 if (MD->isStatic())
745 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000746 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
747 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000748 }
749
Douglas Gregor3257fb52008-12-22 05:46:06 +0000750 // Any other ways we could have found the field in a well-formed
751 // program would have been turned into implicit member expressions
752 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000753 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
754 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000755 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000756
Chris Lattner4b009652007-07-25 00:24:17 +0000757 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000758 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000759 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000760 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000761 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000762 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000763
Steve Naroffd6163f32008-09-05 22:11:13 +0000764 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000765 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000766 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
767 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000768 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
769 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
770 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000771 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000772
Chris Lattnerd9037472009-02-15 01:38:09 +0000773 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner2cb744b2009-02-15 22:43:40 +0000774 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattnerd9037472009-02-15 01:38:09 +0000775
Douglas Gregor48840c72008-12-10 23:01:14 +0000776 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000777 // Warn about constructs like:
778 // if (void *X = foo()) { ... } else { X }.
779 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000780 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
781 Scope *CheckS = S;
782 while (CheckS) {
783 if (CheckS->isWithinElse() &&
784 CheckS->getControlParent()->isDeclScope(Var)) {
785 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000786 ExprError(Diag(Loc, diag::warn_value_always_false)
787 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000788 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000789 ExprError(Diag(Loc, diag::warn_value_always_zero)
790 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000791 break;
792 }
793
794 // Move up one more control parent to check again.
795 CheckS = CheckS->getControlParent();
796 if (CheckS)
797 CheckS = CheckS->getParent();
798 }
799 }
800 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000801
802 // Only create DeclRefExpr's for valid Decl's.
803 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000804 return ExprError();
805
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000806 // If the identifier reference is inside a block, and it refers to a value
807 // that is outside the block, create a BlockDeclRefExpr instead of a
808 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
809 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000810 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000811 // We do not do this for things like enum constants, global variables, etc,
812 // as they do not get snapshotted.
813 //
814 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000815 // The BlocksAttr indicates the variable is bound by-reference.
816 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000817 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000818 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000819
Steve Naroff52059382008-10-10 01:28:17 +0000820 // Variable will be bound by-copy, make it const within the closure.
821 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000822 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000823 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000824 }
825 // If this reference is not in a block or if the referenced variable is
826 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000827
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000828 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000829 bool ValueDependent = false;
830 if (getLangOptions().CPlusPlus) {
831 // C++ [temp.dep.expr]p3:
832 // An id-expression is type-dependent if it contains:
833 // - an identifier that was declared with a dependent type,
834 if (VD->getType()->isDependentType())
835 TypeDependent = true;
836 // - FIXME: a template-id that is dependent,
837 // - a conversion-function-id that specifies a dependent type,
838 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
839 Name.getCXXNameType()->isDependentType())
840 TypeDependent = true;
841 // - a nested-name-specifier that contains a class-name that
842 // names a dependent type.
843 else if (SS && !SS->isEmpty()) {
844 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
845 DC; DC = DC->getParent()) {
846 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000847 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000848 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
849 if (Context.getTypeDeclType(Record)->isDependentType()) {
850 TypeDependent = true;
851 break;
852 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000853 }
854 }
855 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000856
Douglas Gregora5d84612008-12-10 20:57:37 +0000857 // C++ [temp.dep.constexpr]p2:
858 //
859 // An identifier is value-dependent if it is:
860 // - a name declared with a dependent type,
861 if (TypeDependent)
862 ValueDependent = true;
863 // - the name of a non-type template parameter,
864 else if (isa<NonTypeTemplateParmDecl>(VD))
865 ValueDependent = true;
866 // - a constant with integral or enumeration type and is
867 // initialized with an expression that is value-dependent
868 // (FIXME!).
869 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000870
Sebastian Redlcd883f72009-01-18 18:53:16 +0000871 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
872 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000873}
874
Sebastian Redlcd883f72009-01-18 18:53:16 +0000875Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
876 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000877 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000878
Chris Lattner4b009652007-07-25 00:24:17 +0000879 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000880 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000881 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
882 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
883 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000884 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000885
Chris Lattner7e637512008-01-12 08:14:25 +0000886 // Pre-defined identifiers are of type char[x], where x is the length of the
887 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000888 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000889 if (FunctionDecl *FD = getCurFunctionDecl())
890 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000891 else if (ObjCMethodDecl *MD = getCurMethodDecl())
892 Length = MD->getSynthesizedMethodSize();
893 else {
894 Diag(Loc, diag::ext_predef_outside_function);
895 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
896 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
897 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000898
899
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000900 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000901 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000902 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000903 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000904}
905
Sebastian Redlcd883f72009-01-18 18:53:16 +0000906Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000907 llvm::SmallString<16> CharBuffer;
908 CharBuffer.resize(Tok.getLength());
909 const char *ThisTokBegin = &CharBuffer[0];
910 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000911
Chris Lattner4b009652007-07-25 00:24:17 +0000912 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
913 Tok.getLocation(), PP);
914 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000915 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000916
917 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
918
Sebastian Redl75324932009-01-20 22:23:13 +0000919 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
920 Literal.isWide(),
921 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000922}
923
Sebastian Redlcd883f72009-01-18 18:53:16 +0000924Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
925 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000926 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
927 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000928 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000929 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000930 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000931 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000932 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000933
Chris Lattner4b009652007-07-25 00:24:17 +0000934 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000935 // Add padding so that NumericLiteralParser can overread by one character.
936 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000937 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000938
Chris Lattner4b009652007-07-25 00:24:17 +0000939 // Get the spelling of the token, which eliminates trigraphs, etc.
940 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000941
Chris Lattner4b009652007-07-25 00:24:17 +0000942 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
943 Tok.getLocation(), PP);
944 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000945 return ExprError();
946
Chris Lattner1de66eb2007-08-26 03:42:43 +0000947 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000948
Chris Lattner1de66eb2007-08-26 03:42:43 +0000949 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000950 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000951 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000952 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000953 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000954 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000955 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000956 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000957
958 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
959
Ted Kremenekddedbe22007-11-29 00:56:49 +0000960 // isExact will be set by GetFloatValue().
961 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000962 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
963 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000964
Chris Lattner1de66eb2007-08-26 03:42:43 +0000965 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000967 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000968 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000969
Neil Booth7421e9c2007-08-29 22:00:19 +0000970 // long long is a C99 feature.
971 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000972 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000973 Diag(Tok.getLocation(), diag::ext_longlong);
974
Chris Lattner4b009652007-07-25 00:24:17 +0000975 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000976 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000977
Chris Lattner4b009652007-07-25 00:24:17 +0000978 if (Literal.GetIntegerValue(ResultVal)) {
979 // If this value didn't fit into uintmax_t, warn and force to ull.
980 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000981 Ty = Context.UnsignedLongLongTy;
982 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000983 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000984 } else {
985 // If this value fits into a ULL, try to figure out what else it fits into
986 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000987
Chris Lattner4b009652007-07-25 00:24:17 +0000988 // Octal, Hexadecimal, and integers with a U suffix are allowed to
989 // be an unsigned int.
990 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
991
992 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000993 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000994 if (!Literal.isLong && !Literal.isLongLong) {
995 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000996 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000997
Chris Lattner4b009652007-07-25 00:24:17 +0000998 // Does it fit in a unsigned int?
999 if (ResultVal.isIntN(IntSize)) {
1000 // Does it fit in a signed int?
1001 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001002 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001003 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001004 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001005 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001006 }
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001008
Chris Lattner4b009652007-07-25 00:24:17 +00001009 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001010 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001011 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001012
Chris Lattner4b009652007-07-25 00:24:17 +00001013 // Does it fit in a unsigned long?
1014 if (ResultVal.isIntN(LongSize)) {
1015 // Does it fit in a signed long?
1016 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001017 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001018 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001019 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001020 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001021 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001022 }
1023
Chris Lattner4b009652007-07-25 00:24:17 +00001024 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001025 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001026 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001027
Chris Lattner4b009652007-07-25 00:24:17 +00001028 // Does it fit in a unsigned long long?
1029 if (ResultVal.isIntN(LongLongSize)) {
1030 // Does it fit in a signed long long?
1031 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001032 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001033 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001034 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001035 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001036 }
1037 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001038
Chris Lattner4b009652007-07-25 00:24:17 +00001039 // If we still couldn't decide a type, we probably have something that
1040 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001041 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001042 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001043 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001044 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001045 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046
Chris Lattnere4068872008-05-09 05:59:00 +00001047 if (ResultVal.getBitWidth() != Width)
1048 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001049 }
Sebastian Redl75324932009-01-20 22:23:13 +00001050 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001051 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001052
Chris Lattner1de66eb2007-08-26 03:42:43 +00001053 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1054 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001055 Res = new (Context) ImaginaryLiteral(Res,
1056 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001057
1058 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001059}
1060
Sebastian Redlcd883f72009-01-18 18:53:16 +00001061Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1062 SourceLocation R, ExprArg Val) {
1063 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001064 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001065 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001066}
1067
1068/// The UsualUnaryConversions() function is *not* called by this routine.
1069/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001070bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1071 SourceLocation OpLoc,
1072 const SourceRange &ExprRange,
1073 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001074 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001075 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001076 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001077 if (isSizeof)
1078 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1079 return false;
1080 }
1081
1082 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001083 Diag(OpLoc, diag::ext_sizeof_void_type)
1084 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001085 return false;
1086 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001087
Chris Lattner159fe082009-01-24 19:46:37 +00001088 return DiagnoseIncompleteType(OpLoc, exprType,
1089 isSizeof ? diag::err_sizeof_incomplete_type :
1090 diag::err_alignof_incomplete_type,
1091 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001092}
1093
Chris Lattner8d9f7962009-01-24 20:17:12 +00001094bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1095 const SourceRange &ExprRange) {
1096 E = E->IgnoreParens();
1097
1098 // alignof decl is always ok.
1099 if (isa<DeclRefExpr>(E))
1100 return false;
1101
1102 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1103 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1104 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001105 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001106 return true;
1107 }
1108 // Other fields are ok.
1109 return false;
1110 }
1111 }
1112 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1113}
1114
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001115/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1116/// the same for @c alignof and @c __alignof
1117/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001118Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001119Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1120 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001121 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001122 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001123
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001124 QualType ArgTy;
1125 SourceRange Range;
1126 if (isType) {
1127 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1128 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001129
1130 // Verify that the operand is valid.
1131 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1132 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001133 } else {
1134 // Get the end location.
1135 Expr *ArgEx = (Expr *)TyOrEx;
1136 Range = ArgEx->getSourceRange();
1137 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001138
1139 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001140 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001141 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001142 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001143 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1144 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1145 isInvalid = true;
1146 } else {
1147 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1148 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001149
1150 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001151 DeleteExpr(ArgEx);
1152 return ExprError();
1153 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001154 }
1155
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001156 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001157 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001158 Context.getSizeType(), OpLoc,
1159 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001160}
1161
Chris Lattner5110ad52007-08-24 21:41:10 +00001162QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001163 DefaultFunctionArrayConversion(V);
1164
Chris Lattnera16e42d2007-08-26 05:39:26 +00001165 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001166 if (const ComplexType *CT = V->getType()->getAsComplexType())
1167 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001168
1169 // Otherwise they pass through real integer and floating point types here.
1170 if (V->getType()->isArithmeticType())
1171 return V->getType();
1172
1173 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001174 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001175 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001176}
1177
1178
Chris Lattner4b009652007-07-25 00:24:17 +00001179
Sebastian Redl8b769972009-01-19 00:08:26 +00001180Action::OwningExprResult
1181Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1182 tok::TokenKind Kind, ExprArg Input) {
1183 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001184
Chris Lattner4b009652007-07-25 00:24:17 +00001185 UnaryOperator::Opcode Opc;
1186 switch (Kind) {
1187 default: assert(0 && "Unknown unary op!");
1188 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1189 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1190 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001191
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001192 if (getLangOptions().CPlusPlus &&
1193 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1194 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001195 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001196 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1197
1198 // C++ [over.inc]p1:
1199 //
1200 // [...] If the function is a member function with one
1201 // parameter (which shall be of type int) or a non-member
1202 // function with two parameters (the second of which shall be
1203 // of type int), it defines the postfix increment operator ++
1204 // for objects of that type. When the postfix increment is
1205 // called as a result of using the ++ operator, the int
1206 // argument will have value zero.
1207 Expr *Args[2] = {
1208 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001209 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1210 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001211 };
1212
1213 // Build the candidate set for overloading
1214 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001215 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1216 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001217
1218 // Perform overload resolution.
1219 OverloadCandidateSet::iterator Best;
1220 switch (BestViableFunction(CandidateSet, Best)) {
1221 case OR_Success: {
1222 // We found a built-in operator or an overloaded operator.
1223 FunctionDecl *FnDecl = Best->Function;
1224
1225 if (FnDecl) {
1226 // We matched an overloaded operator. Build a call to that
1227 // operator.
1228
1229 // Convert the arguments.
1230 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1231 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001232 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001233 } else {
1234 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001235 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001236 FnDecl->getParamDecl(0)->getType(),
1237 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001238 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001239 }
1240
1241 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001242 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001243 = FnDecl->getType()->getAsFunctionType()->getResultType();
1244 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001245
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001246 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001247 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001248 SourceLocation());
1249 UsualUnaryConversions(FnExpr);
1250
Sebastian Redl8b769972009-01-19 00:08:26 +00001251 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001252 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1253 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001254 } else {
1255 // We matched a built-in operator. Convert the arguments, then
1256 // break out so that we will build the appropriate built-in
1257 // operator node.
1258 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1259 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001260 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001261
1262 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001263 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001264 }
1265
1266 case OR_No_Viable_Function:
1267 // No viable function; fall through to handling this as a
1268 // built-in operator, which will produce an error message for us.
1269 break;
1270
1271 case OR_Ambiguous:
1272 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1273 << UnaryOperator::getOpcodeStr(Opc)
1274 << Arg->getSourceRange();
1275 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001276 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001277 }
1278
1279 // Either we found no viable overloaded operator or we matched a
1280 // built-in operator. In either case, fall through to trying to
1281 // build a built-in operation.
1282 }
1283
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001284 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1285 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001286 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001287 return ExprError();
1288 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001289 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001290}
1291
Sebastian Redl8b769972009-01-19 00:08:26 +00001292Action::OwningExprResult
1293Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1294 ExprArg Idx, SourceLocation RLoc) {
1295 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1296 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001297
Douglas Gregor80723c52008-11-19 17:17:41 +00001298 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001299 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001300 LHSExp->getType()->isEnumeralType() ||
1301 RHSExp->getType()->isRecordType() ||
1302 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001303 // Add the appropriate overloaded operators (C++ [over.match.oper])
1304 // to the candidate set.
1305 OverloadCandidateSet CandidateSet;
1306 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001307 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1308 SourceRange(LLoc, RLoc)))
1309 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001310
Douglas Gregor80723c52008-11-19 17:17:41 +00001311 // Perform overload resolution.
1312 OverloadCandidateSet::iterator Best;
1313 switch (BestViableFunction(CandidateSet, Best)) {
1314 case OR_Success: {
1315 // We found a built-in operator or an overloaded operator.
1316 FunctionDecl *FnDecl = Best->Function;
1317
1318 if (FnDecl) {
1319 // We matched an overloaded operator. Build a call to that
1320 // operator.
1321
1322 // Convert the arguments.
1323 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1324 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1325 PerformCopyInitialization(RHSExp,
1326 FnDecl->getParamDecl(0)->getType(),
1327 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001328 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001329 } else {
1330 // Convert the arguments.
1331 if (PerformCopyInitialization(LHSExp,
1332 FnDecl->getParamDecl(0)->getType(),
1333 "passing") ||
1334 PerformCopyInitialization(RHSExp,
1335 FnDecl->getParamDecl(1)->getType(),
1336 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001337 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001338 }
1339
1340 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001341 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001342 = FnDecl->getType()->getAsFunctionType()->getResultType();
1343 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001344
Douglas Gregor80723c52008-11-19 17:17:41 +00001345 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001346 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001347 SourceLocation());
1348 UsualUnaryConversions(FnExpr);
1349
Sebastian Redl8b769972009-01-19 00:08:26 +00001350 Base.release();
1351 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001352 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001353 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001354 } else {
1355 // We matched a built-in operator. Convert the arguments, then
1356 // break out so that we will build the appropriate built-in
1357 // operator node.
1358 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1359 "passing") ||
1360 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1361 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001362 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001363
1364 break;
1365 }
1366 }
1367
1368 case OR_No_Viable_Function:
1369 // No viable function; fall through to handling this as a
1370 // built-in operator, which will produce an error message for us.
1371 break;
1372
1373 case OR_Ambiguous:
1374 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1375 << "[]"
1376 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1377 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001378 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001379 }
1380
1381 // Either we found no viable overloaded operator or we matched a
1382 // built-in operator. In either case, fall through to trying to
1383 // build a built-in operation.
1384 }
1385
Chris Lattner4b009652007-07-25 00:24:17 +00001386 // Perform default conversions.
1387 DefaultFunctionArrayConversion(LHSExp);
1388 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001389
Chris Lattner4b009652007-07-25 00:24:17 +00001390 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1391
1392 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001393 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001394 // in the subscript position. As a result, we need to derive the array base
1395 // and index from the expression types.
1396 Expr *BaseExpr, *IndexExpr;
1397 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001398 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001399 BaseExpr = LHSExp;
1400 IndexExpr = RHSExp;
1401 // FIXME: need to deal with const...
1402 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001403 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001404 // Handle the uncommon case of "123[Ptr]".
1405 BaseExpr = RHSExp;
1406 IndexExpr = LHSExp;
1407 // FIXME: need to deal with const...
1408 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001409 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1410 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001411 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001412
Chris Lattner4b009652007-07-25 00:24:17 +00001413 // FIXME: need to deal with const...
1414 ResultType = VTy->getElementType();
1415 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001416 return ExprError(Diag(LHSExp->getLocStart(),
1417 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1418 }
Chris Lattner4b009652007-07-25 00:24:17 +00001419 // C99 6.5.2.1p1
1420 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001421 return ExprError(Diag(IndexExpr->getLocStart(),
1422 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001423
1424 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1425 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001426 // void (*)(int)) and pointers to incomplete types. Functions are not
1427 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001428 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001429 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001430 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001431 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001432
Sebastian Redl8b769972009-01-19 00:08:26 +00001433 Base.release();
1434 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001435 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1436 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001437}
1438
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001439QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001440CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001441 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001442 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001443
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001444 // The vector accessor can't exceed the number of elements.
1445 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001446
1447 // This flag determines whether or not the component is one of the four
1448 // special names that indicate a subset of exactly half the elements are
1449 // to be selected.
1450 bool HalvingSwizzle = false;
1451
1452 // This flag determines whether or not CompName has an 's' char prefix,
1453 // indicating that it is a string of hex values to be used as vector indices.
1454 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001455
1456 // Check that we've found one of the special components, or that the component
1457 // names must come from the same set.
1458 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001459 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1460 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001461 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001462 do
1463 compStr++;
1464 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001465 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001466 do
1467 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001468 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001469 }
Nate Begeman1486b502009-01-18 01:47:54 +00001470
1471 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001472 // We didn't get to the end of the string. This means the component names
1473 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001474 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1475 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001476 return QualType();
1477 }
Nate Begeman1486b502009-01-18 01:47:54 +00001478
1479 // Ensure no component accessor exceeds the width of the vector type it
1480 // operates on.
1481 if (!HalvingSwizzle) {
1482 compStr = CompName.getName();
1483
1484 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001485 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001486
1487 while (*compStr) {
1488 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1489 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1490 << baseType << SourceRange(CompLoc);
1491 return QualType();
1492 }
1493 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001494 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001495
Nate Begeman1486b502009-01-18 01:47:54 +00001496 // If this is a halving swizzle, verify that the base type has an even
1497 // number of elements.
1498 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001499 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001500 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001501 return QualType();
1502 }
1503
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001504 // The component accessor looks fine - now we need to compute the actual type.
1505 // The vector type is implied by the component accessor. For example,
1506 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001507 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001508 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001509 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1510 : CompName.getLength();
1511 if (HexSwizzle)
1512 CompSize--;
1513
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001514 if (CompSize == 1)
1515 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001516
Nate Begemanaf6ed502008-04-18 23:10:10 +00001517 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001518 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001519 // diagostics look bad. We want extended vector types to appear built-in.
1520 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1521 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1522 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001523 }
1524 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001525}
1526
Chris Lattner2cb744b2009-02-15 22:43:40 +00001527
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001528/// constructSetterName - Return the setter name for the given
1529/// identifier, i.e. "set" + Name where the initial character of Name
1530/// has been capitalized.
1531// FIXME: Merge with same routine in Parser. But where should this
1532// live?
1533static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1534 const IdentifierInfo *Name) {
1535 llvm::SmallString<100> SelectorName;
1536 SelectorName = "set";
1537 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1538 SelectorName[3] = toupper(SelectorName[3]);
1539 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1540}
1541
Sebastian Redl8b769972009-01-19 00:08:26 +00001542Action::OwningExprResult
1543Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1544 tok::TokenKind OpKind, SourceLocation MemberLoc,
1545 IdentifierInfo &Member) {
1546 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001547 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001548
1549 // Perform default conversions.
1550 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001551
Steve Naroff2cb66382007-07-26 03:11:44 +00001552 QualType BaseType = BaseExpr->getType();
1553 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001554
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001555 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1556 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001557 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001558 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001559 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001560 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001561 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1562 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001563 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001564 return ExprError(Diag(MemberLoc,
1565 diag::err_typecheck_member_reference_arrow)
1566 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001567 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001568
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001569 // Handle field access to simple records. This also handles access to fields
1570 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001571 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001572 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001573 if (DiagnoseIncompleteType(OpLoc, BaseType,
1574 diag::err_typecheck_incomplete_tag,
1575 BaseExpr->getSourceRange()))
1576 return ExprError();
1577
Steve Naroff2cb66382007-07-26 03:11:44 +00001578 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001579 // FIXME: Qualified name lookup for C++ is a bit more complicated
1580 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001581 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001582 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001583 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001584
Douglas Gregor09be81b2009-02-04 17:27:36 +00001585 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001586 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001587 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1588 << &Member << BaseExpr->getSourceRange());
1589 else if (Result.isAmbiguous()) {
1590 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1591 MemberLoc, BaseExpr->getSourceRange());
1592 return ExprError();
1593 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001594 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001595
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001596 // If the decl being referenced had an error, return an error for this
1597 // sub-expr without emitting another error, in order to avoid cascading
1598 // error cases.
1599 if (MemberDecl->isInvalidDecl())
1600 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001601
1602 // Check if referencing a field with __attribute__((deprecated)).
1603 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001604
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001605 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001606 // We may have found a field within an anonymous union or struct
1607 // (C++ [class.union]).
1608 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001609 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001610 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001611
Douglas Gregor82d44772008-12-20 23:49:58 +00001612 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1613 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001614 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001615 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1616 MemberType = Ref->getPointeeType();
1617 else {
1618 unsigned combinedQualifiers =
1619 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001620 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001621 combinedQualifiers &= ~QualType::Const;
1622 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1623 }
Eli Friedman76b49832008-02-06 22:48:16 +00001624
Steve Naroff774e4152009-01-21 00:14:39 +00001625 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1626 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001627 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001628 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001629 Var, MemberLoc,
1630 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001631 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001632 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1633 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001634 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001635 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001636 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001637 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001638 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001639 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001640 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001641 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001642 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1643 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001644
Douglas Gregor82d44772008-12-20 23:49:58 +00001645 // We found a declaration kind that we didn't expect. This is a
1646 // generic error message that tells the user that she can't refer
1647 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001648 return ExprError(Diag(MemberLoc,
1649 diag::err_typecheck_member_reference_unknown)
1650 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001651 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001652
Chris Lattnere9d71612008-07-21 04:59:05 +00001653 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1654 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001655 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001656 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001657 // If the decl being referenced had an error, return an error for this
1658 // sub-expr without emitting another error, in order to avoid cascading
1659 // error cases.
1660 if (IV->isInvalidDecl())
1661 return ExprError();
1662
Chris Lattner2a3bef92009-02-16 17:19:12 +00001663 // Check if referencing a field with __attribute__((deprecated)).
1664 DiagnoseUseOfDeprecatedDecl(IV, MemberLoc);
1665
Steve Naroff774e4152009-01-21 00:14:39 +00001666 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1667 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001668 OpKind == tok::arrow);
1669 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001670 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001671 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001672 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1673 << IFTy->getDecl()->getDeclName() << &Member
1674 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001675 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001676
Chris Lattnere9d71612008-07-21 04:59:05 +00001677 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1678 // pointer to a (potentially qualified) interface type.
1679 const PointerType *PTy;
1680 const ObjCInterfaceType *IFTy;
1681 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1682 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1683 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001684
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001685 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001686 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001687 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001688 MemberLoc, BaseExpr));
1689
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001690 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001691 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1692 E = IFTy->qual_end(); I != E; ++I)
1693 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001694 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001695 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001696
1697 // If that failed, look for an "implicit" property by seeing if the nullary
1698 // selector is implemented.
1699
1700 // FIXME: The logic for looking up nullary and unary selectors should be
1701 // shared with the code in ActOnInstanceMessage.
1702
1703 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1704 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001705
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001706 // If this reference is in an @implementation, check for 'private' methods.
1707 if (!Getter)
1708 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1709 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1710 if (ObjCImplementationDecl *ImpDecl =
1711 ObjCImplementations[ClassDecl->getIdentifier()])
1712 Getter = ImpDecl->getInstanceMethod(Sel);
1713
Steve Naroff04151f32008-10-22 19:16:27 +00001714 // Look through local category implementations associated with the class.
1715 if (!Getter) {
1716 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1717 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1718 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1719 }
1720 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001721 if (Getter) {
1722 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001723 // will look for the matching setter, in case it is needed.
1724 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1725 &Member);
1726 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1727 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1728 if (!Setter) {
1729 // If this reference is in an @implementation, also check for 'private'
1730 // methods.
1731 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1732 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1733 if (ObjCImplementationDecl *ImpDecl =
1734 ObjCImplementations[ClassDecl->getIdentifier()])
1735 Setter = ImpDecl->getInstanceMethod(SetterSel);
1736 }
1737 // Look through local category implementations associated with the class.
1738 if (!Setter) {
1739 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1740 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1741 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1742 }
1743 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001744
1745 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001746 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1747 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001748 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001749
1750 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1751 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001752 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001753 // Handle properties on qualified "id" protocols.
1754 const ObjCQualifiedIdType *QIdTy;
1755 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1756 // Check protocols on qualified interfaces.
1757 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001758 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001759 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001760 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001761 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001762 // Also must look for a getter name which uses property syntax.
1763 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1764 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001765 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1766 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001767 }
1768 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001769
1770 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1771 << &Member << BaseType);
1772 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001773 // Handle 'field access' to vectors, such as 'V.xx'.
1774 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001775 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1776 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001777 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001778 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1779 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001780 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001781
1782 return ExprError(Diag(MemberLoc,
1783 diag::err_typecheck_member_reference_struct_union)
1784 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001785}
1786
Douglas Gregor3257fb52008-12-22 05:46:06 +00001787/// ConvertArgumentsForCall - Converts the arguments specified in
1788/// Args/NumArgs to the parameter types of the function FDecl with
1789/// function prototype Proto. Call is the call expression itself, and
1790/// Fn is the function expression. For a C++ member function, this
1791/// routine does not attempt to convert the object argument. Returns
1792/// true if the call is ill-formed.
1793bool
1794Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1795 FunctionDecl *FDecl,
1796 const FunctionTypeProto *Proto,
1797 Expr **Args, unsigned NumArgs,
1798 SourceLocation RParenLoc) {
1799 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1800 // assignment, to the types of the corresponding parameter, ...
1801 unsigned NumArgsInProto = Proto->getNumArgs();
1802 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001803 bool Invalid = false;
1804
Douglas Gregor3257fb52008-12-22 05:46:06 +00001805 // If too few arguments are available (and we don't have default
1806 // arguments for the remaining parameters), don't make the call.
1807 if (NumArgs < NumArgsInProto) {
1808 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1809 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1810 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1811 // Use default arguments for missing arguments
1812 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001813 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001814 }
1815
1816 // If too many are passed and not variadic, error on the extras and drop
1817 // them.
1818 if (NumArgs > NumArgsInProto) {
1819 if (!Proto->isVariadic()) {
1820 Diag(Args[NumArgsInProto]->getLocStart(),
1821 diag::err_typecheck_call_too_many_args)
1822 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1823 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1824 Args[NumArgs-1]->getLocEnd());
1825 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001826 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001827 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001828 }
1829 NumArgsToCheck = NumArgsInProto;
1830 }
1831
1832 // Continue to check argument types (even if we have too few/many args).
1833 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1834 QualType ProtoArgType = Proto->getArgType(i);
1835
1836 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001837 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001838 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001839
1840 // Pass the argument.
1841 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1842 return true;
1843 } else
1844 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001845 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001846 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001847
Douglas Gregor3257fb52008-12-22 05:46:06 +00001848 Call->setArg(i, Arg);
1849 }
1850
1851 // If this is a variadic call, handle args passed through "...".
1852 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001853 VariadicCallType CallType = VariadicFunction;
1854 if (Fn->getType()->isBlockPointerType())
1855 CallType = VariadicBlock; // Block
1856 else if (isa<MemberExpr>(Fn))
1857 CallType = VariadicMethod;
1858
Douglas Gregor3257fb52008-12-22 05:46:06 +00001859 // Promote the arguments (C99 6.5.2.2p7).
1860 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1861 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001862 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001863 Call->setArg(i, Arg);
1864 }
1865 }
1866
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001867 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001868}
1869
Steve Naroff87d58b42007-09-16 03:34:24 +00001870/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001871/// This provides the location of the left/right parens and a list of comma
1872/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001873Action::OwningExprResult
1874Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1875 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001876 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001877 unsigned NumArgs = args.size();
1878 Expr *Fn = static_cast<Expr *>(fn.release());
1879 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001880 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001881 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001882 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001883
Douglas Gregor3257fb52008-12-22 05:46:06 +00001884 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001885 // Determine whether this is a dependent call inside a C++ template,
1886 // in which case we won't do any semantic analysis now.
1887 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1888 bool Dependent = false;
1889 if (Fn->isTypeDependent())
1890 Dependent = true;
1891 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1892 Dependent = true;
1893
1894 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001895 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001896 Context.DependentTy, RParenLoc));
1897
1898 // Determine whether this is a call to an object (C++ [over.call.object]).
1899 if (Fn->getType()->isRecordType())
1900 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1901 CommaLocs, RParenLoc));
1902
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001903 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001904 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1905 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1906 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001907 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1908 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001909 }
1910
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001911 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001912 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001913 Expr *FnExpr = Fn;
1914 bool ADL = true;
1915 while (true) {
1916 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1917 FnExpr = IcExpr->getSubExpr();
1918 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001919 // Parentheses around a function disable ADL
1920 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001921 ADL = false;
1922 FnExpr = PExpr->getSubExpr();
1923 } else if (isa<UnaryOperator>(FnExpr) &&
1924 cast<UnaryOperator>(FnExpr)->getOpcode()
1925 == UnaryOperator::AddrOf) {
1926 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001927 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1928 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1929 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1930 break;
1931 } else if (UnresolvedFunctionNameExpr *DepName
1932 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1933 UnqualifiedName = DepName->getName();
1934 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001935 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001936 // Any kind of name that does not refer to a declaration (or
1937 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1938 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001939 break;
1940 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001941 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001942
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001943 OverloadedFunctionDecl *Ovl = 0;
1944 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001945 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001946 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1947 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001948
Douglas Gregorfcb19192009-02-11 23:02:49 +00001949 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001950 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001951 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001952 ADL = false;
1953
Douglas Gregorfcb19192009-02-11 23:02:49 +00001954 // We don't perform ADL in C.
1955 if (!getLangOptions().CPlusPlus)
1956 ADL = false;
1957
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001958 if (Ovl || ADL) {
1959 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1960 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001961 NumArgs, CommaLocs, RParenLoc, ADL);
1962 if (!FDecl)
1963 return ExprError();
1964
1965 // Update Fn to refer to the actual function selected.
1966 Expr *NewFn = 0;
1967 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001968 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001969 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1970 QDRExpr->getLocation(),
1971 false, false,
1972 QDRExpr->getSourceRange().getBegin());
1973 else
1974 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1975 Fn->getSourceRange().getBegin());
1976 Fn->Destroy(Context);
1977 Fn = NewFn;
1978 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001979 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001980
1981 // Promote the function operand.
1982 UsualUnaryConversions(Fn);
1983
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001984 // Make the call expr early, before semantic checks. This guarantees cleanup
1985 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001986 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1987 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00001988 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
1989 Args, NumArgs,
1990 Context.BoolTy,
1991 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001992
Steve Naroffd6163f32008-09-05 22:11:13 +00001993 const FunctionType *FuncT;
1994 if (!Fn->getType()->isBlockPointerType()) {
1995 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1996 // have type pointer to function".
1997 const PointerType *PT = Fn->getType()->getAsPointerType();
1998 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001999 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2000 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002001 FuncT = PT->getPointeeType()->getAsFunctionType();
2002 } else { // This is a block call.
2003 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2004 getAsFunctionType();
2005 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002006 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002007 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2008 << Fn->getType() << Fn->getSourceRange());
2009
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002010 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002011 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002012
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002013 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002014 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2015 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002016 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002017 } else {
2018 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002019
Steve Naroffdb65e052007-08-28 23:30:39 +00002020 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002021 for (unsigned i = 0; i != NumArgs; i++) {
2022 Expr *Arg = Args[i];
2023 DefaultArgumentPromotion(Arg);
2024 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002025 }
Chris Lattner4b009652007-07-25 00:24:17 +00002026 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002027
Douglas Gregor3257fb52008-12-22 05:46:06 +00002028 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2029 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002030 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2031 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002032
Chris Lattner2e64c072007-08-10 20:18:51 +00002033 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002034 if (FDecl)
2035 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002036
Sebastian Redl8b769972009-01-19 00:08:26 +00002037 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002038}
2039
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002040Action::OwningExprResult
2041Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2042 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002043 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002044 QualType literalType = QualType::getFromOpaquePtr(Ty);
2045 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002046 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002047 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002048
Eli Friedman8c2173d2008-05-20 05:22:08 +00002049 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002050 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002051 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2052 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002053 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2054 diag::err_typecheck_decl_incomplete_type,
2055 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002056 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002057
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002058 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002059 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002060 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002061
Chris Lattnere5cb5862008-12-04 23:50:19 +00002062 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002063 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002064 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002065 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002066 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002067 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002068 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2069 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002070}
2071
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002072Action::OwningExprResult
2073Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2074 InitListDesignations &Designators,
2075 SourceLocation RBraceLoc) {
2076 unsigned NumInit = initlist.size();
2077 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002078
Steve Naroff0acc9c92007-09-15 18:49:24 +00002079 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002080 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002081
Steve Naroff774e4152009-01-21 00:14:39 +00002082 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002083 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002084 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002085 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002086}
2087
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002088/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002089bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002090 UsualUnaryConversions(castExpr);
2091
2092 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2093 // type needs to be scalar.
2094 if (castType->isVoidType()) {
2095 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002096 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2097 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002098 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002099 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2100 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2101 (castType->isStructureType() || castType->isUnionType())) {
2102 // GCC struct/union extension: allow cast to self.
2103 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2104 << castType << castExpr->getSourceRange();
2105 } else if (castType->isUnionType()) {
2106 // GCC cast to union extension
2107 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2108 RecordDecl::field_iterator Field, FieldEnd;
2109 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2110 Field != FieldEnd; ++Field) {
2111 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2112 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2113 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2114 << castExpr->getSourceRange();
2115 break;
2116 }
2117 }
2118 if (Field == FieldEnd)
2119 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2120 << castExpr->getType() << castExpr->getSourceRange();
2121 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002122 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002123 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002124 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002125 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002126 } else if (!castExpr->getType()->isScalarType() &&
2127 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002128 return Diag(castExpr->getLocStart(),
2129 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002130 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002131 } else if (castExpr->getType()->isVectorType()) {
2132 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2133 return true;
2134 } else if (castType->isVectorType()) {
2135 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2136 return true;
2137 }
2138 return false;
2139}
2140
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002141bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002142 assert(VectorTy->isVectorType() && "Not a vector type!");
2143
2144 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002145 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002146 return Diag(R.getBegin(),
2147 Ty->isVectorType() ?
2148 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002149 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002150 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002151 } else
2152 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002153 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002154 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002155
2156 return false;
2157}
2158
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002159Action::OwningExprResult
2160Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2161 SourceLocation RParenLoc, ExprArg Op) {
2162 assert((Ty != 0) && (Op.get() != 0) &&
2163 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002164
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002165 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002166 QualType castType = QualType::getFromOpaquePtr(Ty);
2167
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002168 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002169 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002170 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002171 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002172}
2173
Chris Lattner98a425c2007-11-26 01:40:58 +00002174/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2175/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002176inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2177 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2178 UsualUnaryConversions(cond);
2179 UsualUnaryConversions(lex);
2180 UsualUnaryConversions(rex);
2181 QualType condT = cond->getType();
2182 QualType lexT = lex->getType();
2183 QualType rexT = rex->getType();
2184
2185 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002186 if (!cond->isTypeDependent()) {
2187 if (!condT->isScalarType()) { // C99 6.5.15p2
2188 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2189 return QualType();
2190 }
Chris Lattner4b009652007-07-25 00:24:17 +00002191 }
Chris Lattner992ae932008-01-06 22:42:25 +00002192
2193 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002194 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2195 return Context.DependentTy;
2196
Chris Lattner992ae932008-01-06 22:42:25 +00002197 // If both operands have arithmetic type, do the usual arithmetic conversions
2198 // to find a common type: C99 6.5.15p3,5.
2199 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002200 UsualArithmeticConversions(lex, rex);
2201 return lex->getType();
2202 }
Chris Lattner992ae932008-01-06 22:42:25 +00002203
2204 // If both operands are the same structure or union type, the result is that
2205 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002206 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002207 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002208 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002209 // "If both the operands have structure or union type, the result has
2210 // that type." This implies that CV qualifiers are dropped.
2211 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002212 }
Chris Lattner992ae932008-01-06 22:42:25 +00002213
2214 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002215 // The following || allows only one side to be void (a GCC-ism).
2216 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002217 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002218 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2219 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002220 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002221 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2222 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002223 ImpCastExprToType(lex, Context.VoidTy);
2224 ImpCastExprToType(rex, Context.VoidTy);
2225 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002226 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002227 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2228 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002229 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2230 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002231 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002232 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002233 return lexT;
2234 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002235 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2236 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002237 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002238 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002239 return rexT;
2240 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002241 // Handle the case where both operands are pointers before we handle null
2242 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002243 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2244 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2245 // get the "pointed to" types
2246 QualType lhptee = LHSPT->getPointeeType();
2247 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002248
Chris Lattner71225142007-07-31 21:27:01 +00002249 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2250 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002251 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002252 // Figure out necessary qualifiers (C99 6.5.15p6)
2253 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002254 QualType destType = Context.getPointerType(destPointee);
2255 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2256 ImpCastExprToType(rex, destType); // promote to void*
2257 return destType;
2258 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002259 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002260 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002261 QualType destType = Context.getPointerType(destPointee);
2262 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2263 ImpCastExprToType(rex, destType); // promote to void*
2264 return destType;
2265 }
Chris Lattner4b009652007-07-25 00:24:17 +00002266
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002267 QualType compositeType = lexT;
2268
2269 // If either type is an Objective-C object type then check
2270 // compatibility according to Objective-C.
2271 if (Context.isObjCObjectPointerType(lexT) ||
2272 Context.isObjCObjectPointerType(rexT)) {
2273 // If both operands are interfaces and either operand can be
2274 // assigned to the other, use that type as the composite
2275 // type. This allows
2276 // xxx ? (A*) a : (B*) b
2277 // where B is a subclass of A.
2278 //
2279 // Additionally, as for assignment, if either type is 'id'
2280 // allow silent coercion. Finally, if the types are
2281 // incompatible then make sure to use 'id' as the composite
2282 // type so the result is acceptable for sending messages to.
2283
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002284 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2285 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002286 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2287 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2288 if (LHSIface && RHSIface &&
2289 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2290 compositeType = lexT;
2291 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002292 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002293 compositeType = rexT;
Steve Naroff17c03822009-02-12 17:52:19 +00002294 } else if (Context.isObjCIdStructType(lhptee) ||
2295 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002296 compositeType = Context.getObjCIdType();
2297 } else {
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002298 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2299 << lexT << rexT
2300 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002301 QualType incompatTy = Context.getObjCIdType();
2302 ImpCastExprToType(lex, incompatTy);
2303 ImpCastExprToType(rex, incompatTy);
2304 return incompatTy;
2305 }
2306 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2307 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002308 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002309 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002310 // In this situation, we assume void* type. No especially good
2311 // reason, but this is what gcc does, and we do have to pick
2312 // to get a consistent AST.
2313 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002314 ImpCastExprToType(lex, incompatTy);
2315 ImpCastExprToType(rex, incompatTy);
2316 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002317 }
2318 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002319 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2320 // differently qualified versions of compatible types, the result type is
2321 // a pointer to an appropriately qualified version of the *composite*
2322 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002323 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002324 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002325 ImpCastExprToType(lex, compositeType);
2326 ImpCastExprToType(rex, compositeType);
2327 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002328 }
Chris Lattner4b009652007-07-25 00:24:17 +00002329 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002330 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2331 // evaluates to "struct objc_object *" (and is handled above when comparing
2332 // id with statically typed objects).
2333 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2334 // GCC allows qualified id and any Objective-C type to devolve to
2335 // id. Currently localizing to here until clear this should be
2336 // part of ObjCQualifiedIdTypesAreCompatible.
2337 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2338 (lexT->isObjCQualifiedIdType() &&
2339 Context.isObjCObjectPointerType(rexT)) ||
2340 (rexT->isObjCQualifiedIdType() &&
2341 Context.isObjCObjectPointerType(lexT))) {
2342 // FIXME: This is not the correct composite type. This only
2343 // happens to work because id can more or less be used anywhere,
2344 // however this may change the type of method sends.
2345 // FIXME: gcc adds some type-checking of the arguments and emits
2346 // (confusing) incompatible comparison warnings in some
2347 // cases. Investigate.
2348 QualType compositeType = Context.getObjCIdType();
2349 ImpCastExprToType(lex, compositeType);
2350 ImpCastExprToType(rex, compositeType);
2351 return compositeType;
2352 }
2353 }
2354
Steve Naroff3eac7692008-09-10 19:17:48 +00002355 // Selection between block pointer types is ok as long as they are the same.
2356 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2357 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2358 return lexT;
2359
Chris Lattner992ae932008-01-06 22:42:25 +00002360 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002361 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002362 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002363 return QualType();
2364}
2365
Steve Naroff87d58b42007-09-16 03:34:24 +00002366/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002367/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002368Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2369 SourceLocation ColonLoc,
2370 ExprArg Cond, ExprArg LHS,
2371 ExprArg RHS) {
2372 Expr *CondExpr = (Expr *) Cond.get();
2373 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002374
2375 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2376 // was the condition.
2377 bool isLHSNull = LHSExpr == 0;
2378 if (isLHSNull)
2379 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002380
2381 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002382 RHSExpr, QuestionLoc);
2383 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002384 return ExprError();
2385
2386 Cond.release();
2387 LHS.release();
2388 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002389 return Owned(new (Context) ConditionalOperator(CondExpr,
2390 isLHSNull ? 0 : LHSExpr,
2391 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002392}
2393
Chris Lattner4b009652007-07-25 00:24:17 +00002394
2395// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2396// being closely modeled after the C99 spec:-). The odd characteristic of this
2397// routine is it effectively iqnores the qualifiers on the top level pointee.
2398// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2399// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002400Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002401Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2402 QualType lhptee, rhptee;
2403
2404 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002405 lhptee = lhsType->getAsPointerType()->getPointeeType();
2406 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002407
2408 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002409 lhptee = Context.getCanonicalType(lhptee);
2410 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002411
Chris Lattner005ed752008-01-04 18:04:52 +00002412 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002413
2414 // C99 6.5.16.1p1: This following citation is common to constraints
2415 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2416 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002417 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002418 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002419 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002420
2421 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2422 // incomplete type and the other is a pointer to a qualified or unqualified
2423 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002424 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002425 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002426 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002427
2428 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002429 assert(rhptee->isFunctionType());
2430 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002431 }
2432
2433 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002434 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002435 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002436
2437 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002438 assert(lhptee->isFunctionType());
2439 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002440 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002441
2442 // Check for ObjC interfaces
2443 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2444 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2445 if (LHSIface && RHSIface &&
2446 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2447 return ConvTy;
2448
2449 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002450 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002451 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002452 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002453 return ConvTy;
2454
Chris Lattner4b009652007-07-25 00:24:17 +00002455 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2456 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002457 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2458 rhptee.getUnqualifiedType()))
2459 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002460 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002461}
2462
Steve Naroff3454b6c2008-09-04 15:10:53 +00002463/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2464/// block pointer types are compatible or whether a block and normal pointer
2465/// are compatible. It is more restrict than comparing two function pointer
2466// types.
2467Sema::AssignConvertType
2468Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2469 QualType rhsType) {
2470 QualType lhptee, rhptee;
2471
2472 // get the "pointed to" type (ignoring qualifiers at the top level)
2473 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2474 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2475
2476 // make sure we operate on the canonical type
2477 lhptee = Context.getCanonicalType(lhptee);
2478 rhptee = Context.getCanonicalType(rhptee);
2479
2480 AssignConvertType ConvTy = Compatible;
2481
2482 // For blocks we enforce that qualifiers are identical.
2483 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2484 ConvTy = CompatiblePointerDiscardsQualifiers;
2485
2486 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2487 return IncompatibleBlockPointer;
2488 return ConvTy;
2489}
2490
Chris Lattner4b009652007-07-25 00:24:17 +00002491/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2492/// has code to accommodate several GCC extensions when type checking
2493/// pointers. Here are some objectionable examples that GCC considers warnings:
2494///
2495/// int a, *pint;
2496/// short *pshort;
2497/// struct foo *pfoo;
2498///
2499/// pint = pshort; // warning: assignment from incompatible pointer type
2500/// a = pint; // warning: assignment makes integer from pointer without a cast
2501/// pint = a; // warning: assignment makes pointer from integer without a cast
2502/// pint = pfoo; // warning: assignment from incompatible pointer type
2503///
2504/// As a result, the code for dealing with pointers is more complex than the
2505/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002506///
Chris Lattner005ed752008-01-04 18:04:52 +00002507Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002508Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002509 // Get canonical types. We're not formatting these types, just comparing
2510 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002511 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2512 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002513
2514 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002515 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002516
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002517 // If the left-hand side is a reference type, then we are in a
2518 // (rare!) case where we've allowed the use of references in C,
2519 // e.g., as a parameter type in a built-in function. In this case,
2520 // just make sure that the type referenced is compatible with the
2521 // right-hand side type. The caller is responsible for adjusting
2522 // lhsType so that the resulting expression does not have reference
2523 // type.
2524 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2525 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002526 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002527 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002528 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002529
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002530 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2531 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002532 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002533 // Relax integer conversions like we do for pointers below.
2534 if (rhsType->isIntegerType())
2535 return IntToPointer;
2536 if (lhsType->isIntegerType())
2537 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002538 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002539 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002540
Nate Begemanc5f0f652008-07-14 18:02:46 +00002541 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002542 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002543 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2544 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002545 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002546
Nate Begemanc5f0f652008-07-14 18:02:46 +00002547 // If we are allowing lax vector conversions, and LHS and RHS are both
2548 // vectors, the total size only needs to be the same. This is a bitcast;
2549 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002550 if (getLangOptions().LaxVectorConversions &&
2551 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002552 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002553 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002554 }
2555 return Incompatible;
2556 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002557
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002558 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002559 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002560
Chris Lattner390564e2008-04-07 06:49:41 +00002561 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002562 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002563 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002564
Chris Lattner390564e2008-04-07 06:49:41 +00002565 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002566 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002567
Steve Naroffa982c712008-09-29 18:10:17 +00002568 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002569 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002570 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002571
2572 // Treat block pointers as objects.
2573 if (getLangOptions().ObjC1 &&
2574 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2575 return Compatible;
2576 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002577 return Incompatible;
2578 }
2579
2580 if (isa<BlockPointerType>(lhsType)) {
2581 if (rhsType->isIntegerType())
2582 return IntToPointer;
2583
Steve Naroffa982c712008-09-29 18:10:17 +00002584 // Treat block pointers as objects.
2585 if (getLangOptions().ObjC1 &&
2586 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2587 return Compatible;
2588
Steve Naroff3454b6c2008-09-04 15:10:53 +00002589 if (rhsType->isBlockPointerType())
2590 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2591
2592 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2593 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002594 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002595 }
Chris Lattner1853da22008-01-04 23:18:45 +00002596 return Incompatible;
2597 }
2598
Chris Lattner390564e2008-04-07 06:49:41 +00002599 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002600 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002601 if (lhsType == Context.BoolTy)
2602 return Compatible;
2603
2604 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002605 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002606
Chris Lattner390564e2008-04-07 06:49:41 +00002607 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002608 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002609
2610 if (isa<BlockPointerType>(lhsType) &&
2611 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002612 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002613 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002614 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002615
Chris Lattner1853da22008-01-04 23:18:45 +00002616 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002617 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002618 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002619 }
2620 return Incompatible;
2621}
2622
Chris Lattner005ed752008-01-04 18:04:52 +00002623Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002624Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002625 if (getLangOptions().CPlusPlus) {
2626 if (!lhsType->isRecordType()) {
2627 // C++ 5.17p3: If the left operand is not of class type, the
2628 // expression is implicitly converted (C++ 4) to the
2629 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002630 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2631 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002632 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002633 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002634 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002635 }
2636
2637 // FIXME: Currently, we fall through and treat C++ classes like C
2638 // structures.
2639 }
2640
Steve Naroffcdee22d2007-11-27 17:58:44 +00002641 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2642 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002643 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2644 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002645 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002646 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002647 return Compatible;
2648 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002649
2650 // We don't allow conversion of non-null-pointer constants to integers.
2651 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2652 return IntToBlockPointer;
2653
Chris Lattner5f505bf2007-10-16 02:55:40 +00002654 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002655 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002656 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002657 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002658 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002659 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002660 if (!lhsType->isReferenceType())
2661 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002662
Chris Lattner005ed752008-01-04 18:04:52 +00002663 Sema::AssignConvertType result =
2664 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002665
2666 // C99 6.5.16.1p2: The value of the right operand is converted to the
2667 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002668 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2669 // so that we can use references in built-in functions even in C.
2670 // The getNonReferenceType() call makes sure that the resulting expression
2671 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002672 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002673 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002674 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002675}
2676
Chris Lattner005ed752008-01-04 18:04:52 +00002677Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002678Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2679 return CheckAssignmentConstraints(lhsType, rhsType);
2680}
2681
Chris Lattner1eafdea2008-11-18 01:30:42 +00002682QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002683 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002684 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002685 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002686 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002687}
2688
Chris Lattner1eafdea2008-11-18 01:30:42 +00002689inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002690 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002691 // For conversion purposes, we ignore any qualifiers.
2692 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002693 QualType lhsType =
2694 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2695 QualType rhsType =
2696 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002697
Nate Begemanc5f0f652008-07-14 18:02:46 +00002698 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002699 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002700 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002701
Nate Begemanc5f0f652008-07-14 18:02:46 +00002702 // Handle the case of a vector & extvector type of the same size and element
2703 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002704 if (getLangOptions().LaxVectorConversions) {
2705 // FIXME: Should we warn here?
2706 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002707 if (const VectorType *RV = rhsType->getAsVectorType())
2708 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002709 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002710 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002711 }
2712 }
2713 }
2714
Nate Begemanc5f0f652008-07-14 18:02:46 +00002715 // If the lhs is an extended vector and the rhs is a scalar of the same type
2716 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002717 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002718 QualType eltType = V->getElementType();
2719
2720 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2721 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2722 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002723 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002724 return lhsType;
2725 }
2726 }
2727
Nate Begemanc5f0f652008-07-14 18:02:46 +00002728 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002729 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002730 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002731 QualType eltType = V->getElementType();
2732
2733 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2734 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2735 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002736 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002737 return rhsType;
2738 }
2739 }
2740
Chris Lattner4b009652007-07-25 00:24:17 +00002741 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002742 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002743 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002744 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002745 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002746}
2747
Chris Lattner4b009652007-07-25 00:24:17 +00002748inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002749 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002750{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002751 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002752 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002753
Steve Naroff8f708362007-08-24 19:07:16 +00002754 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002755
Chris Lattner4b009652007-07-25 00:24:17 +00002756 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002757 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002758 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002759}
2760
2761inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002762 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002763{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002764 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2765 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2766 return CheckVectorOperands(Loc, lex, rex);
2767 return InvalidOperands(Loc, lex, rex);
2768 }
Chris Lattner4b009652007-07-25 00:24:17 +00002769
Steve Naroff8f708362007-08-24 19:07:16 +00002770 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002771
Chris Lattner4b009652007-07-25 00:24:17 +00002772 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002773 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002774 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002775}
2776
2777inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002778 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002779{
2780 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002781 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002782
Steve Naroff8f708362007-08-24 19:07:16 +00002783 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002784
Chris Lattner4b009652007-07-25 00:24:17 +00002785 // handle the common case first (both operands are arithmetic).
2786 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002787 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002788
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002789 // Put any potential pointer into PExp
2790 Expr* PExp = lex, *IExp = rex;
2791 if (IExp->getType()->isPointerType())
2792 std::swap(PExp, IExp);
2793
2794 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2795 if (IExp->getType()->isIntegerType()) {
2796 // Check for arithmetic on pointers to incomplete types
2797 if (!PTy->getPointeeType()->isObjectType()) {
2798 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002799 if (getLangOptions().CPlusPlus) {
2800 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2801 << lex->getSourceRange() << rex->getSourceRange();
2802 return QualType();
2803 }
2804
2805 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002806 Diag(Loc, diag::ext_gnu_void_ptr)
2807 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002808 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002809 if (getLangOptions().CPlusPlus) {
2810 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2811 << lex->getType() << lex->getSourceRange();
2812 return QualType();
2813 }
2814
2815 // GNU extension: arithmetic on pointer to function
2816 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002817 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002818 } else {
2819 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2820 diag::err_typecheck_arithmetic_incomplete_type,
2821 lex->getSourceRange(), SourceRange(),
2822 lex->getType());
2823 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002824 }
2825 }
2826 return PExp->getType();
2827 }
2828 }
2829
Chris Lattner1eafdea2008-11-18 01:30:42 +00002830 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002831}
2832
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002833// C99 6.5.6
2834QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002835 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002836 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002837 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002838
Steve Naroff8f708362007-08-24 19:07:16 +00002839 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002840
Chris Lattnerf6da2912007-12-09 21:53:25 +00002841 // Enforce type constraints: C99 6.5.6p3.
2842
2843 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002844 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002845 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002846
2847 // Either ptr - int or ptr - ptr.
2848 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002849 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002850
Chris Lattnerf6da2912007-12-09 21:53:25 +00002851 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002852 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002853 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002854 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002855 Diag(Loc, diag::ext_gnu_void_ptr)
2856 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002857 } else if (lpointee->isFunctionType()) {
2858 if (getLangOptions().CPlusPlus) {
2859 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2860 << lex->getType() << lex->getSourceRange();
2861 return QualType();
2862 }
2863
2864 // GNU extension: arithmetic on pointer to function
2865 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2866 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002867 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002868 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002869 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002870 return QualType();
2871 }
2872 }
2873
2874 // The result type of a pointer-int computation is the pointer type.
2875 if (rex->getType()->isIntegerType())
2876 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002877
Chris Lattnerf6da2912007-12-09 21:53:25 +00002878 // Handle pointer-pointer subtractions.
2879 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002880 QualType rpointee = RHSPTy->getPointeeType();
2881
Chris Lattnerf6da2912007-12-09 21:53:25 +00002882 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002883 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002884 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002885 if (rpointee->isVoidType()) {
2886 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002887 Diag(Loc, diag::ext_gnu_void_ptr)
2888 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002889 } else if (rpointee->isFunctionType()) {
2890 if (getLangOptions().CPlusPlus) {
2891 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2892 << rex->getType() << rex->getSourceRange();
2893 return QualType();
2894 }
2895
2896 // GNU extension: arithmetic on pointer to function
2897 if (!lpointee->isFunctionType())
2898 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2899 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002900 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002901 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002902 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002903 return QualType();
2904 }
2905 }
2906
2907 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002908 if (!Context.typesAreCompatible(
2909 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2910 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002911 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002912 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002913 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002914 return QualType();
2915 }
2916
2917 return Context.getPointerDiffType();
2918 }
2919 }
2920
Chris Lattner1eafdea2008-11-18 01:30:42 +00002921 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002922}
2923
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002924// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002925QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002926 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002927 // C99 6.5.7p2: Each of the operands shall have integer type.
2928 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002929 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002930
Chris Lattner2c8bff72007-12-12 05:47:28 +00002931 // Shifts don't perform usual arithmetic conversions, they just do integer
2932 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002933 if (!isCompAssign)
2934 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002935 UsualUnaryConversions(rex);
2936
2937 // "The type of the result is that of the promoted left operand."
2938 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002939}
2940
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002941// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002942QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002943 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002944 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002945 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002946
Chris Lattner254f3bc2007-08-26 01:18:55 +00002947 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002948 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2949 UsualArithmeticConversions(lex, rex);
2950 else {
2951 UsualUnaryConversions(lex);
2952 UsualUnaryConversions(rex);
2953 }
Chris Lattner4b009652007-07-25 00:24:17 +00002954 QualType lType = lex->getType();
2955 QualType rType = rex->getType();
2956
Ted Kremenek486509e2007-10-29 17:13:39 +00002957 // For non-floating point types, check for self-comparisons of the form
2958 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2959 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002960 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002961 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2962 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002963 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002964 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002965 }
2966
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002967 // The result of comparisons is 'bool' in C++, 'int' in C.
2968 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2969
Chris Lattner254f3bc2007-08-26 01:18:55 +00002970 if (isRelational) {
2971 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002972 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002973 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002974 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002975 if (lType->isFloatingType()) {
2976 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002977 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002978 }
2979
Chris Lattner254f3bc2007-08-26 01:18:55 +00002980 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002981 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002982 }
Chris Lattner4b009652007-07-25 00:24:17 +00002983
Chris Lattner22be8422007-08-26 01:10:14 +00002984 bool LHSIsNull = lex->isNullPointerConstant(Context);
2985 bool RHSIsNull = rex->isNullPointerConstant(Context);
2986
Chris Lattner254f3bc2007-08-26 01:18:55 +00002987 // All of the following pointer related warnings are GCC extensions, except
2988 // when handling null pointer constants. One day, we can consider making them
2989 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002990 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002991 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002992 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002993 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002994 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002995
Steve Naroff3b435622007-11-13 14:57:38 +00002996 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002997 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2998 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002999 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003000 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003001 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003002 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003003 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003004 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003005 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003006 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003007 // Handle block pointer types.
3008 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3009 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3010 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3011
3012 if (!LHSIsNull && !RHSIsNull &&
3013 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003014 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003015 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003016 }
3017 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003018 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003019 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003020 // Allow block pointers to be compared with null pointer constants.
3021 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3022 (lType->isPointerType() && rType->isBlockPointerType())) {
3023 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003024 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003025 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003026 }
3027 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003028 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003029 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003030
Steve Naroff936c4362008-06-03 14:04:54 +00003031 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003032 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003033 const PointerType *LPT = lType->getAsPointerType();
3034 const PointerType *RPT = rType->getAsPointerType();
3035 bool LPtrToVoid = LPT ?
3036 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3037 bool RPtrToVoid = RPT ?
3038 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3039
3040 if (!LPtrToVoid && !RPtrToVoid &&
3041 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003042 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003043 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003044 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003045 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003046 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003047 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003048 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003049 }
Steve Naroff936c4362008-06-03 14:04:54 +00003050 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3051 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003052 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003053 } else {
3054 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003055 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003056 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003057 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003058 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003059 }
Steve Naroff936c4362008-06-03 14:04:54 +00003060 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003061 }
Steve Naroff936c4362008-06-03 14:04:54 +00003062 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3063 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003064 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003065 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003066 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003067 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003068 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003069 }
Steve Naroff936c4362008-06-03 14:04:54 +00003070 if (lType->isIntegerType() &&
3071 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003072 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003073 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003074 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003075 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003076 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003077 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003078 // Handle block pointers.
3079 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3080 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003081 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003082 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003083 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003084 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003085 }
3086 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3087 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003088 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003089 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003090 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003091 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003092 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003093 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003094}
3095
Nate Begemanc5f0f652008-07-14 18:02:46 +00003096/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3097/// operates on extended vector types. Instead of producing an IntTy result,
3098/// like a scalar comparison, a vector comparison produces a vector of integer
3099/// types.
3100QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003101 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003102 bool isRelational) {
3103 // Check to make sure we're operating on vectors of the same type and width,
3104 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003105 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003106 if (vType.isNull())
3107 return vType;
3108
3109 QualType lType = lex->getType();
3110 QualType rType = rex->getType();
3111
3112 // For non-floating point types, check for self-comparisons of the form
3113 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3114 // often indicate logic errors in the program.
3115 if (!lType->isFloatingType()) {
3116 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3117 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3118 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003119 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003120 }
3121
3122 // Check for comparisons of floating point operands using != and ==.
3123 if (!isRelational && lType->isFloatingType()) {
3124 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003125 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003126 }
3127
3128 // Return the type for the comparison, which is the same as vector type for
3129 // integer vectors, or an integer type of identical size and number of
3130 // elements for floating point vectors.
3131 if (lType->isIntegerType())
3132 return lType;
3133
3134 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003135 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003136 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003137 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003138 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3139 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3140
3141 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3142 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003143 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3144}
3145
Chris Lattner4b009652007-07-25 00:24:17 +00003146inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003147 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003148{
3149 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003150 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003151
Steve Naroff8f708362007-08-24 19:07:16 +00003152 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003153
3154 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003155 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003156 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003157}
3158
3159inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003160 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003161{
3162 UsualUnaryConversions(lex);
3163 UsualUnaryConversions(rex);
3164
Eli Friedmanbea3f842008-05-13 20:16:47 +00003165 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003166 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003167 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003168}
3169
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003170/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3171/// is a read-only property; return true if so. A readonly property expression
3172/// depends on various declarations and thus must be treated specially.
3173///
3174static bool IsReadonlyProperty(Expr *E, Sema &S)
3175{
3176 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3177 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3178 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3179 QualType BaseType = PropExpr->getBase()->getType();
3180 if (const PointerType *PTy = BaseType->getAsPointerType())
3181 if (const ObjCInterfaceType *IFTy =
3182 PTy->getPointeeType()->getAsObjCInterfaceType())
3183 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3184 if (S.isPropertyReadonly(PDecl, IFace))
3185 return true;
3186 }
3187 }
3188 return false;
3189}
3190
Chris Lattner4c2642c2008-11-18 01:22:49 +00003191/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3192/// emit an error and return true. If so, return false.
3193static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003194 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3195 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3196 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003197 if (IsLV == Expr::MLV_Valid)
3198 return false;
3199
3200 unsigned Diag = 0;
3201 bool NeedType = false;
3202 switch (IsLV) { // C99 6.5.16p2
3203 default: assert(0 && "Unknown result from isModifiableLvalue!");
3204 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003205 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003206 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3207 NeedType = true;
3208 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003209 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003210 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3211 NeedType = true;
3212 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003213 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003214 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3215 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003216 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003217 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3218 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003219 case Expr::MLV_IncompleteType:
3220 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003221 return S.DiagnoseIncompleteType(Loc, E->getType(),
3222 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3223 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003224 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003225 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3226 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003227 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003228 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3229 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003230 case Expr::MLV_ReadonlyProperty:
3231 Diag = diag::error_readonly_property_assignment;
3232 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003233 case Expr::MLV_NoSetterProperty:
3234 Diag = diag::error_nosetter_property_assignment;
3235 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003236 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003237
Chris Lattner4c2642c2008-11-18 01:22:49 +00003238 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003239 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003240 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003241 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003242 return true;
3243}
3244
3245
3246
3247// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003248QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3249 SourceLocation Loc,
3250 QualType CompoundType) {
3251 // Verify that LHS is a modifiable lvalue, and emit error if not.
3252 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003253 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003254
3255 QualType LHSType = LHS->getType();
3256 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003257
Chris Lattner005ed752008-01-04 18:04:52 +00003258 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003259 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003260 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003261 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003262 // Special case of NSObject attributes on c-style pointer types.
3263 if (ConvTy == IncompatiblePointer &&
3264 ((Context.isObjCNSObjectType(LHSType) &&
3265 Context.isObjCObjectPointerType(RHSType)) ||
3266 (Context.isObjCNSObjectType(RHSType) &&
3267 Context.isObjCObjectPointerType(LHSType))))
3268 ConvTy = Compatible;
3269
Chris Lattner34c85082008-08-21 18:04:13 +00003270 // If the RHS is a unary plus or minus, check to see if they = and + are
3271 // right next to each other. If so, the user may have typo'd "x =+ 4"
3272 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003273 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003274 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3275 RHSCheck = ICE->getSubExpr();
3276 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3277 if ((UO->getOpcode() == UnaryOperator::Plus ||
3278 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003279 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003280 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003281 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003282 Diag(Loc, diag::warn_not_compound_assign)
3283 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3284 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003285 }
3286 } else {
3287 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003288 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003289 }
Chris Lattner005ed752008-01-04 18:04:52 +00003290
Chris Lattner1eafdea2008-11-18 01:30:42 +00003291 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3292 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003293 return QualType();
3294
Chris Lattner4b009652007-07-25 00:24:17 +00003295 // C99 6.5.16p3: The type of an assignment expression is the type of the
3296 // left operand unless the left operand has qualified type, in which case
3297 // it is the unqualified version of the type of the left operand.
3298 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3299 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003300 // C++ 5.17p1: the type of the assignment expression is that of its left
3301 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003302 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003303}
3304
Chris Lattner1eafdea2008-11-18 01:30:42 +00003305// C99 6.5.17
3306QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3307 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003308
3309 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003310 DefaultFunctionArrayConversion(RHS);
3311 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003312}
3313
3314/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3315/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003316QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3317 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003318 QualType ResType = Op->getType();
3319 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003320
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003321 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3322 // Decrement of bool is not allowed.
3323 if (!isInc) {
3324 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3325 return QualType();
3326 }
3327 // Increment of bool sets it to true, but is deprecated.
3328 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3329 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003330 // OK!
3331 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3332 // C99 6.5.2.4p2, 6.5.6p2
3333 if (PT->getPointeeType()->isObjectType()) {
3334 // Pointer to object is ok!
3335 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003336 if (getLangOptions().CPlusPlus) {
3337 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3338 << Op->getSourceRange();
3339 return QualType();
3340 }
3341
3342 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003343 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003344 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003345 if (getLangOptions().CPlusPlus) {
3346 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3347 << Op->getType() << Op->getSourceRange();
3348 return QualType();
3349 }
3350
3351 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003352 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003353 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003354 } else {
3355 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3356 diag::err_typecheck_arithmetic_incomplete_type,
3357 Op->getSourceRange(), SourceRange(),
3358 ResType);
3359 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003360 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003361 } else if (ResType->isComplexType()) {
3362 // C99 does not support ++/-- on complex types, we allow as an extension.
3363 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003364 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003365 } else {
3366 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003367 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003368 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003369 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003370 // At this point, we know we have a real, complex or pointer type.
3371 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003372 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003373 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003374 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003375}
3376
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003377/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003378/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003379/// where the declaration is needed for type checking. We only need to
3380/// handle cases when the expression references a function designator
3381/// or is an lvalue. Here are some examples:
3382/// - &(x) => x
3383/// - &*****f => f for f a function designator.
3384/// - &s.xx => s
3385/// - &s.zz[1].yy -> s, if zz is an array
3386/// - *(x + 1) -> x, if x is an array
3387/// - &"123"[2] -> 0
3388/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003389static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003390 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003391 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003392 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003393 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003394 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003395 // Fields cannot be declared with a 'register' storage class.
3396 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003397 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003398 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003399 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003400 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003401 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003402
Douglas Gregord2baafd2008-10-21 16:13:35 +00003403 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003404 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003405 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003406 return 0;
3407 else
3408 return VD;
3409 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003410 case Stmt::UnaryOperatorClass: {
3411 UnaryOperator *UO = cast<UnaryOperator>(E);
3412
3413 switch(UO->getOpcode()) {
3414 case UnaryOperator::Deref: {
3415 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003416 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3417 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3418 if (!VD || VD->getType()->isPointerType())
3419 return 0;
3420 return VD;
3421 }
3422 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003423 }
3424 case UnaryOperator::Real:
3425 case UnaryOperator::Imag:
3426 case UnaryOperator::Extension:
3427 return getPrimaryDecl(UO->getSubExpr());
3428 default:
3429 return 0;
3430 }
3431 }
3432 case Stmt::BinaryOperatorClass: {
3433 BinaryOperator *BO = cast<BinaryOperator>(E);
3434
3435 // Handle cases involving pointer arithmetic. The result of an
3436 // Assign or AddAssign is not an lvalue so they can be ignored.
3437
3438 // (x + n) or (n + x) => x
3439 if (BO->getOpcode() == BinaryOperator::Add) {
3440 if (BO->getLHS()->getType()->isPointerType()) {
3441 return getPrimaryDecl(BO->getLHS());
3442 } else if (BO->getRHS()->getType()->isPointerType()) {
3443 return getPrimaryDecl(BO->getRHS());
3444 }
3445 }
3446
3447 return 0;
3448 }
Chris Lattner4b009652007-07-25 00:24:17 +00003449 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003450 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003451 case Stmt::ImplicitCastExprClass:
3452 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003453 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003454 default:
3455 return 0;
3456 }
3457}
3458
3459/// CheckAddressOfOperand - The operand of & must be either a function
3460/// designator or an lvalue designating an object. If it is an lvalue, the
3461/// object cannot be declared with storage class register or be a bit field.
3462/// Note: The usual conversions are *not* applied to the operand of the &
3463/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003464/// In C++, the operand might be an overloaded function name, in which case
3465/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003466QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003467 if (op->isTypeDependent())
3468 return Context.DependentTy;
3469
Steve Naroff9c6c3592008-01-13 17:10:08 +00003470 if (getLangOptions().C99) {
3471 // Implement C99-only parts of addressof rules.
3472 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3473 if (uOp->getOpcode() == UnaryOperator::Deref)
3474 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3475 // (assuming the deref expression is valid).
3476 return uOp->getSubExpr()->getType();
3477 }
3478 // Technically, there should be a check for array subscript
3479 // expressions here, but the result of one is always an lvalue anyway.
3480 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003481 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003482 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003483
Chris Lattner4b009652007-07-25 00:24:17 +00003484 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003485 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3486 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003487 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3488 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003489 return QualType();
3490 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003491 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003492 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3493 if (Field->isBitField()) {
3494 Diag(OpLoc, diag::err_typecheck_address_of)
3495 << "bit-field" << op->getSourceRange();
3496 return QualType();
3497 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003498 }
3499 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003500 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3501 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003502 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003503 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003504 return QualType();
3505 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003506 // We have an lvalue with a decl. Make sure the decl is not declared
3507 // with the register storage-class specifier.
3508 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3509 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003510 Diag(OpLoc, diag::err_typecheck_address_of)
3511 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003512 return QualType();
3513 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003514 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003515 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003516 } else if (isa<FieldDecl>(dcl)) {
3517 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003518 // Could be a pointer to member, though, if there is an explicit
3519 // scope qualifier for the class.
3520 if (isa<QualifiedDeclRefExpr>(op)) {
3521 DeclContext *Ctx = dcl->getDeclContext();
3522 if (Ctx && Ctx->isRecord())
3523 return Context.getMemberPointerType(op->getType(),
3524 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3525 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003526 } else if (isa<FunctionDecl>(dcl)) {
3527 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003528 // As above.
3529 if (isa<QualifiedDeclRefExpr>(op)) {
3530 DeclContext *Ctx = dcl->getDeclContext();
3531 if (Ctx && Ctx->isRecord())
3532 return Context.getMemberPointerType(op->getType(),
3533 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3534 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003535 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003536 else
Chris Lattner4b009652007-07-25 00:24:17 +00003537 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003538 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003539
Chris Lattner4b009652007-07-25 00:24:17 +00003540 // If the operand has type "type", the result has type "pointer to type".
3541 return Context.getPointerType(op->getType());
3542}
3543
Chris Lattnerda5c0872008-11-23 09:13:29 +00003544QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3545 UsualUnaryConversions(Op);
3546 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003547
Chris Lattnerda5c0872008-11-23 09:13:29 +00003548 // Note that per both C89 and C99, this is always legal, even if ptype is an
3549 // incomplete type or void. It would be possible to warn about dereferencing
3550 // a void pointer, but it's completely well-defined, and such a warning is
3551 // unlikely to catch any mistakes.
3552 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003553 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003554
Chris Lattner77d52da2008-11-20 06:06:08 +00003555 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003556 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003557 return QualType();
3558}
3559
3560static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3561 tok::TokenKind Kind) {
3562 BinaryOperator::Opcode Opc;
3563 switch (Kind) {
3564 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003565 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3566 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003567 case tok::star: Opc = BinaryOperator::Mul; break;
3568 case tok::slash: Opc = BinaryOperator::Div; break;
3569 case tok::percent: Opc = BinaryOperator::Rem; break;
3570 case tok::plus: Opc = BinaryOperator::Add; break;
3571 case tok::minus: Opc = BinaryOperator::Sub; break;
3572 case tok::lessless: Opc = BinaryOperator::Shl; break;
3573 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3574 case tok::lessequal: Opc = BinaryOperator::LE; break;
3575 case tok::less: Opc = BinaryOperator::LT; break;
3576 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3577 case tok::greater: Opc = BinaryOperator::GT; break;
3578 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3579 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3580 case tok::amp: Opc = BinaryOperator::And; break;
3581 case tok::caret: Opc = BinaryOperator::Xor; break;
3582 case tok::pipe: Opc = BinaryOperator::Or; break;
3583 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3584 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3585 case tok::equal: Opc = BinaryOperator::Assign; break;
3586 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3587 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3588 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3589 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3590 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3591 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3592 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3593 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3594 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3595 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3596 case tok::comma: Opc = BinaryOperator::Comma; break;
3597 }
3598 return Opc;
3599}
3600
3601static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3602 tok::TokenKind Kind) {
3603 UnaryOperator::Opcode Opc;
3604 switch (Kind) {
3605 default: assert(0 && "Unknown unary op!");
3606 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3607 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3608 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3609 case tok::star: Opc = UnaryOperator::Deref; break;
3610 case tok::plus: Opc = UnaryOperator::Plus; break;
3611 case tok::minus: Opc = UnaryOperator::Minus; break;
3612 case tok::tilde: Opc = UnaryOperator::Not; break;
3613 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003614 case tok::kw___real: Opc = UnaryOperator::Real; break;
3615 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3616 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3617 }
3618 return Opc;
3619}
3620
Douglas Gregord7f915e2008-11-06 23:29:22 +00003621/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3622/// operator @p Opc at location @c TokLoc. This routine only supports
3623/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003624Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3625 unsigned Op,
3626 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003627 QualType ResultTy; // Result type of the binary operator.
3628 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3629 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3630
3631 switch (Opc) {
3632 default:
3633 assert(0 && "Unknown binary expr!");
3634 case BinaryOperator::Assign:
3635 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3636 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003637 case BinaryOperator::PtrMemD:
3638 case BinaryOperator::PtrMemI:
3639 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3640 Opc == BinaryOperator::PtrMemI);
3641 break;
3642 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003643 case BinaryOperator::Div:
3644 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3645 break;
3646 case BinaryOperator::Rem:
3647 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3648 break;
3649 case BinaryOperator::Add:
3650 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3651 break;
3652 case BinaryOperator::Sub:
3653 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3654 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003655 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003656 case BinaryOperator::Shr:
3657 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3658 break;
3659 case BinaryOperator::LE:
3660 case BinaryOperator::LT:
3661 case BinaryOperator::GE:
3662 case BinaryOperator::GT:
3663 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3664 break;
3665 case BinaryOperator::EQ:
3666 case BinaryOperator::NE:
3667 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3668 break;
3669 case BinaryOperator::And:
3670 case BinaryOperator::Xor:
3671 case BinaryOperator::Or:
3672 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3673 break;
3674 case BinaryOperator::LAnd:
3675 case BinaryOperator::LOr:
3676 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3677 break;
3678 case BinaryOperator::MulAssign:
3679 case BinaryOperator::DivAssign:
3680 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3681 if (!CompTy.isNull())
3682 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3683 break;
3684 case BinaryOperator::RemAssign:
3685 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3686 if (!CompTy.isNull())
3687 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3688 break;
3689 case BinaryOperator::AddAssign:
3690 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3691 if (!CompTy.isNull())
3692 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3693 break;
3694 case BinaryOperator::SubAssign:
3695 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3696 if (!CompTy.isNull())
3697 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3698 break;
3699 case BinaryOperator::ShlAssign:
3700 case BinaryOperator::ShrAssign:
3701 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3702 if (!CompTy.isNull())
3703 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3704 break;
3705 case BinaryOperator::AndAssign:
3706 case BinaryOperator::XorAssign:
3707 case BinaryOperator::OrAssign:
3708 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3709 if (!CompTy.isNull())
3710 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3711 break;
3712 case BinaryOperator::Comma:
3713 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3714 break;
3715 }
3716 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003717 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003718 if (CompTy.isNull())
3719 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3720 else
3721 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003722 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003723}
3724
Chris Lattner4b009652007-07-25 00:24:17 +00003725// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003726Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3727 tok::TokenKind Kind,
3728 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003729 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003730 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003731
Steve Naroff87d58b42007-09-16 03:34:24 +00003732 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3733 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003734
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003735 // If either expression is type-dependent, just build the AST.
3736 // FIXME: We'll need to perform some caching of the result of name
3737 // lookup for operator+.
3738 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003739 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3740 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003741 Context.DependentTy,
3742 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003743 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003744 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3745 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003746 }
3747
Sebastian Redl95216a62009-02-07 00:15:38 +00003748 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003749 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3750 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003751 // If this is one of the assignment operators, we only perform
3752 // overload resolution if the left-hand side is a class or
3753 // enumeration type (C++ [expr.ass]p3).
3754 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3755 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3756 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3757 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003758
Douglas Gregord7f915e2008-11-06 23:29:22 +00003759 // Determine which overloaded operator we're dealing with.
3760 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003761 // Overloading .* is not possible.
3762 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003763 OO_Star, OO_Slash, OO_Percent,
3764 OO_Plus, OO_Minus,
3765 OO_LessLess, OO_GreaterGreater,
3766 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3767 OO_EqualEqual, OO_ExclaimEqual,
3768 OO_Amp,
3769 OO_Caret,
3770 OO_Pipe,
3771 OO_AmpAmp,
3772 OO_PipePipe,
3773 OO_Equal, OO_StarEqual,
3774 OO_SlashEqual, OO_PercentEqual,
3775 OO_PlusEqual, OO_MinusEqual,
3776 OO_LessLessEqual, OO_GreaterGreaterEqual,
3777 OO_AmpEqual, OO_CaretEqual,
3778 OO_PipeEqual,
3779 OO_Comma
3780 };
3781 OverloadedOperatorKind OverOp = OverOps[Opc];
3782
Douglas Gregor5ed15042008-11-18 23:14:02 +00003783 // Add the appropriate overloaded operators (C++ [over.match.oper])
3784 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003785 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003786 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003787 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3788 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003789
3790 // Perform overload resolution.
3791 OverloadCandidateSet::iterator Best;
3792 switch (BestViableFunction(CandidateSet, Best)) {
3793 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003794 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003795 FunctionDecl *FnDecl = Best->Function;
3796
Douglas Gregor70d26122008-11-12 17:17:38 +00003797 if (FnDecl) {
3798 // We matched an overloaded operator. Build a call to that
3799 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003800
Douglas Gregor70d26122008-11-12 17:17:38 +00003801 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003802 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3803 if (PerformObjectArgumentInitialization(lhs, Method) ||
3804 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3805 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003806 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003807 } else {
3808 // Convert the arguments.
3809 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3810 "passing") ||
3811 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3812 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003813 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003814 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003815
Douglas Gregor70d26122008-11-12 17:17:38 +00003816 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003817 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003818 = FnDecl->getType()->getAsFunctionType()->getResultType();
3819 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003820
Douglas Gregor70d26122008-11-12 17:17:38 +00003821 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003822 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3823 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003824 UsualUnaryConversions(FnExpr);
3825
Ted Kremenek362abcd2009-02-09 20:51:47 +00003826 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003827 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003828 } else {
3829 // We matched a built-in operator. Convert the arguments, then
3830 // break out so that we will build the appropriate built-in
3831 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003832 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3833 Best->Conversions[0], "passing") ||
3834 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3835 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003836 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003837
3838 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003839 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003840 }
3841
3842 case OR_No_Viable_Function:
3843 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003844 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003845 break;
3846
3847 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003848 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3849 << BinaryOperator::getOpcodeStr(Opc)
3850 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003851 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003852 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003853 }
3854
Douglas Gregor70d26122008-11-12 17:17:38 +00003855 // Either we found no viable overloaded operator or we matched a
3856 // built-in operator. In either case, fall through to trying to
3857 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003858 }
3859
Douglas Gregord7f915e2008-11-06 23:29:22 +00003860 // Build a built-in binary operation.
3861 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003862}
3863
3864// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003865Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3866 tok::TokenKind Op, ExprArg input) {
3867 // FIXME: Input is modified later, but smart pointer not reassigned.
3868 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003869 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003870
3871 if (getLangOptions().CPlusPlus &&
3872 (Input->getType()->isRecordType()
3873 || Input->getType()->isEnumeralType())) {
3874 // Determine which overloaded operator we're dealing with.
3875 static const OverloadedOperatorKind OverOps[] = {
3876 OO_None, OO_None,
3877 OO_PlusPlus, OO_MinusMinus,
3878 OO_Amp, OO_Star,
3879 OO_Plus, OO_Minus,
3880 OO_Tilde, OO_Exclaim,
3881 OO_None, OO_None,
3882 OO_None,
3883 OO_None
3884 };
3885 OverloadedOperatorKind OverOp = OverOps[Opc];
3886
3887 // Add the appropriate overloaded operators (C++ [over.match.oper])
3888 // to the candidate set.
3889 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003890 if (OverOp != OO_None &&
3891 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3892 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003893
3894 // Perform overload resolution.
3895 OverloadCandidateSet::iterator Best;
3896 switch (BestViableFunction(CandidateSet, Best)) {
3897 case OR_Success: {
3898 // We found a built-in operator or an overloaded operator.
3899 FunctionDecl *FnDecl = Best->Function;
3900
3901 if (FnDecl) {
3902 // We matched an overloaded operator. Build a call to that
3903 // operator.
3904
3905 // Convert the arguments.
3906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3907 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003908 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003909 } else {
3910 // Convert the arguments.
3911 if (PerformCopyInitialization(Input,
3912 FnDecl->getParamDecl(0)->getType(),
3913 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003914 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003915 }
3916
3917 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003918 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003919 = FnDecl->getType()->getAsFunctionType()->getResultType();
3920 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003921
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003922 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003923 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3924 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003925 UsualUnaryConversions(FnExpr);
3926
Sebastian Redl8b769972009-01-19 00:08:26 +00003927 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003928 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003929 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003930 } else {
3931 // We matched a built-in operator. Convert the arguments, then
3932 // break out so that we will build the appropriate built-in
3933 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003934 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3935 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003936 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003937
3938 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003939 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003940 }
3941
3942 case OR_No_Viable_Function:
3943 // No viable function; fall through to handling this as a
3944 // built-in operator, which will produce an error message for us.
3945 break;
3946
3947 case OR_Ambiguous:
3948 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3949 << UnaryOperator::getOpcodeStr(Opc)
3950 << Input->getSourceRange();
3951 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003952 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003953 }
3954
3955 // Either we found no viable overloaded operator or we matched a
3956 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003957 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003958 }
3959
Chris Lattner4b009652007-07-25 00:24:17 +00003960 QualType resultType;
3961 switch (Opc) {
3962 default:
3963 assert(0 && "Unimplemented unary expr!");
3964 case UnaryOperator::PreInc:
3965 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003966 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3967 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003968 break;
3969 case UnaryOperator::AddrOf:
3970 resultType = CheckAddressOfOperand(Input, OpLoc);
3971 break;
3972 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003973 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003974 resultType = CheckIndirectionOperand(Input, OpLoc);
3975 break;
3976 case UnaryOperator::Plus:
3977 case UnaryOperator::Minus:
3978 UsualUnaryConversions(Input);
3979 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003980 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3981 break;
3982 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3983 resultType->isEnumeralType())
3984 break;
3985 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3986 Opc == UnaryOperator::Plus &&
3987 resultType->isPointerType())
3988 break;
3989
Sebastian Redl8b769972009-01-19 00:08:26 +00003990 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3991 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003992 case UnaryOperator::Not: // bitwise complement
3993 UsualUnaryConversions(Input);
3994 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003995 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3996 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3997 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003998 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003999 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004000 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004001 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4002 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004003 break;
4004 case UnaryOperator::LNot: // logical negation
4005 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4006 DefaultFunctionArrayConversion(Input);
4007 resultType = Input->getType();
4008 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004009 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4010 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004011 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004012 // In C++, it's bool. C++ 5.3.1p8
4013 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004014 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004015 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004016 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00004017 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00004018 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004019 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004020 resultType = Input->getType();
4021 break;
4022 }
4023 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004024 return ExprError();
4025 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004026 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004027}
4028
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004029/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4030Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004031 SourceLocation LabLoc,
4032 IdentifierInfo *LabelII) {
4033 // Look up the record for this label identifier.
4034 LabelStmt *&LabelDecl = LabelMap[LabelII];
4035
Daniel Dunbar879788d2008-08-04 16:51:22 +00004036 // If we haven't seen this label yet, create a forward reference. It
4037 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004038 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004039 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004040
4041 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004042 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4043 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004044}
4045
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004046Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004047 SourceLocation RPLoc) { // "({..})"
4048 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4049 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4050 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4051
Eli Friedmanbc941e12009-01-24 23:09:00 +00004052 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4053 if (isFileScope) {
4054 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4055 }
4056
Chris Lattner4b009652007-07-25 00:24:17 +00004057 // FIXME: there are a variety of strange constraints to enforce here, for
4058 // example, it is not possible to goto into a stmt expression apparently.
4059 // More semantic analysis is needed.
4060
4061 // FIXME: the last statement in the compount stmt has its value used. We
4062 // should not warn about it being unused.
4063
4064 // If there are sub stmts in the compound stmt, take the type of the last one
4065 // as the type of the stmtexpr.
4066 QualType Ty = Context.VoidTy;
4067
Chris Lattner200964f2008-07-26 19:51:01 +00004068 if (!Compound->body_empty()) {
4069 Stmt *LastStmt = Compound->body_back();
4070 // If LastStmt is a label, skip down through into the body.
4071 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4072 LastStmt = Label->getSubStmt();
4073
4074 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004075 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004076 }
Chris Lattner4b009652007-07-25 00:24:17 +00004077
Steve Naroff774e4152009-01-21 00:14:39 +00004078 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004079}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004080
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004081Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4082 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004083 SourceLocation TypeLoc,
4084 TypeTy *argty,
4085 OffsetOfComponent *CompPtr,
4086 unsigned NumComponents,
4087 SourceLocation RPLoc) {
4088 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4089 assert(!ArgTy.isNull() && "Missing type argument!");
4090
4091 // We must have at least one component that refers to the type, and the first
4092 // one is known to be a field designator. Verify that the ArgTy represents
4093 // a struct/union/class.
4094 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004095 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004096
4097 // Otherwise, create a compound literal expression as the base, and
4098 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004099 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004100 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004101 IList->setType(ArgTy);
4102 Expr *Res =
4103 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4104
Chris Lattnerb37522e2007-08-31 21:49:13 +00004105 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4106 // GCC extension, diagnose them.
4107 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004108 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4109 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004110
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004111 for (unsigned i = 0; i != NumComponents; ++i) {
4112 const OffsetOfComponent &OC = CompPtr[i];
4113 if (OC.isBrackets) {
4114 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004115 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004116 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004117 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004118 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004119 }
4120
Chris Lattner2af6a802007-08-30 17:59:59 +00004121 // FIXME: C++: Verify that operator[] isn't overloaded.
4122
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004123 // C99 6.5.2.1p1
4124 Expr *Idx = static_cast<Expr*>(OC.U.E);
4125 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004126 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4127 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004128
Steve Naroff774e4152009-01-21 00:14:39 +00004129 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4130 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004131 continue;
4132 }
4133
4134 const RecordType *RC = Res->getType()->getAsRecordType();
4135 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004136 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004137 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004138 }
4139
4140 // Get the decl corresponding to this.
4141 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004142 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004143 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4144 LookupMemberName)
4145 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004146 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004147 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4148 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004149
4150 // FIXME: C++: Verify that MemberDecl isn't a static field.
4151 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004152 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4153 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004154 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4155 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004156 }
4157
Steve Naroff774e4152009-01-21 00:14:39 +00004158 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4159 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004160}
4161
4162
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004163Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004164 TypeTy *arg1, TypeTy *arg2,
4165 SourceLocation RPLoc) {
4166 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4167 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4168
4169 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4170
Steve Naroff774e4152009-01-21 00:14:39 +00004171 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4172 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004173}
4174
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004175Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004176 ExprTy *expr1, ExprTy *expr2,
4177 SourceLocation RPLoc) {
4178 Expr *CondExpr = static_cast<Expr*>(cond);
4179 Expr *LHSExpr = static_cast<Expr*>(expr1);
4180 Expr *RHSExpr = static_cast<Expr*>(expr2);
4181
4182 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4183
4184 // The conditional expression is required to be a constant expression.
4185 llvm::APSInt condEval(32);
4186 SourceLocation ExpLoc;
4187 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004188 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4189 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004190
4191 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4192 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4193 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004194 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4195 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004196}
4197
Steve Naroff52a81c02008-09-03 18:15:37 +00004198//===----------------------------------------------------------------------===//
4199// Clang Extensions.
4200//===----------------------------------------------------------------------===//
4201
4202/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004203void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004204 // Analyze block parameters.
4205 BlockSemaInfo *BSI = new BlockSemaInfo();
4206
4207 // Add BSI to CurBlock.
4208 BSI->PrevBlockInfo = CurBlock;
4209 CurBlock = BSI;
4210
4211 BSI->ReturnType = 0;
4212 BSI->TheScope = BlockScope;
4213
Steve Naroff52059382008-10-10 01:28:17 +00004214 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004215 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004216}
4217
Mike Stumpc1fddff2009-02-04 22:31:32 +00004218void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4219 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4220
4221 if (ParamInfo.getNumTypeObjects() == 0
4222 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4223 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4224
4225 // The type is entirely optional as well, if none, use DependentTy.
4226 if (T.isNull())
4227 T = Context.DependentTy;
4228
4229 // The parameter list is optional, if there was none, assume ().
4230 if (!T->isFunctionType())
4231 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4232
4233 CurBlock->hasPrototype = true;
4234 CurBlock->isVariadic = false;
4235 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4236 .getTypePtr();
4237
4238 if (!RetTy->isDependentType())
4239 CurBlock->ReturnType = RetTy;
4240 return;
4241 }
4242
Steve Naroff52a81c02008-09-03 18:15:37 +00004243 // Analyze arguments to block.
4244 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4245 "Not a function declarator!");
4246 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004247
Steve Naroff52059382008-10-10 01:28:17 +00004248 CurBlock->hasPrototype = FTI.hasPrototype;
4249 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004250
4251 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4252 // no arguments, not a function that takes a single void argument.
4253 if (FTI.hasPrototype &&
4254 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4255 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4256 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4257 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004258 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004259 } else if (FTI.hasPrototype) {
4260 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004261 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4262 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004263 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4264
4265 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4266 .getTypePtr();
4267
4268 if (!RetTy->isDependentType())
4269 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004270 }
Steve Naroff52059382008-10-10 01:28:17 +00004271 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4272
4273 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4274 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4275 // If this has an identifier, add it to the scope stack.
4276 if ((*AI)->getIdentifier())
4277 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004278}
4279
4280/// ActOnBlockError - If there is an error parsing a block, this callback
4281/// is invoked to pop the information about the block from the action impl.
4282void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4283 // Ensure that CurBlock is deleted.
4284 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4285
4286 // Pop off CurBlock, handle nested blocks.
4287 CurBlock = CurBlock->PrevBlockInfo;
4288
4289 // FIXME: Delete the ParmVarDecl objects as well???
4290
4291}
4292
4293/// ActOnBlockStmtExpr - This is called when the body of a block statement
4294/// literal was successfully completed. ^(int x){...}
4295Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4296 Scope *CurScope) {
4297 // Ensure that CurBlock is deleted.
4298 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004299 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004300
Steve Naroff52059382008-10-10 01:28:17 +00004301 PopDeclContext();
4302
Steve Naroff52a81c02008-09-03 18:15:37 +00004303 // Pop off CurBlock, handle nested blocks.
4304 CurBlock = CurBlock->PrevBlockInfo;
4305
4306 QualType RetTy = Context.VoidTy;
4307 if (BSI->ReturnType)
4308 RetTy = QualType(BSI->ReturnType, 0);
4309
4310 llvm::SmallVector<QualType, 8> ArgTypes;
4311 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4312 ArgTypes.push_back(BSI->Params[i]->getType());
4313
4314 QualType BlockTy;
4315 if (!BSI->hasPrototype)
4316 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4317 else
4318 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004319 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004320
4321 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004322
Steve Naroff95029d92008-10-08 18:44:00 +00004323 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004324 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004325}
4326
Nate Begemanbd881ef2008-01-30 20:50:20 +00004327/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004328/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004329/// The number of arguments has already been validated to match the number of
4330/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004331static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4332 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004333 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004334 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004335 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4336 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004337
4338 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004339 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004340 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004341 return true;
4342}
4343
4344Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4345 SourceLocation *CommaLocs,
4346 SourceLocation BuiltinLoc,
4347 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004348 // __builtin_overload requires at least 2 arguments
4349 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004350 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4351 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004352
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004353 // The first argument is required to be a constant expression. It tells us
4354 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004355 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004356 Expr *NParamsExpr = Args[0];
4357 llvm::APSInt constEval(32);
4358 SourceLocation ExpLoc;
4359 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004360 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4361 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004362
4363 // Verify that the number of parameters is > 0
4364 unsigned NumParams = constEval.getZExtValue();
4365 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004366 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4367 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004368 // Verify that we have at least 1 + NumParams arguments to the builtin.
4369 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004370 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4371 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004372
4373 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004374 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004375 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004376 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4377 // UsualUnaryConversions will convert the function DeclRefExpr into a
4378 // pointer to function.
4379 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004380 const FunctionTypeProto *FnType = 0;
4381 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4382 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004383
4384 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4385 // parameters, and the number of parameters must match the value passed to
4386 // the builtin.
4387 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004388 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4389 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004390
4391 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004392 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004393 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004394 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004395 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004396 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4397 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004398 // Remember our match, and continue processing the remaining arguments
4399 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004400 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004401 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004402 BuiltinLoc, RParenLoc);
4403 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004404 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004405 // Return the newly created OverloadExpr node, if we succeded in matching
4406 // exactly one of the candidate functions.
4407 if (OE)
4408 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004409
4410 // If we didn't find a matching function Expr in the __builtin_overload list
4411 // the return an error.
4412 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004413 for (unsigned i = 0; i != NumParams; ++i) {
4414 if (i != 0) typeNames += ", ";
4415 typeNames += Args[i+1]->getType().getAsString();
4416 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004417
Chris Lattner77d52da2008-11-20 06:06:08 +00004418 return Diag(BuiltinLoc, diag::err_overload_no_match)
4419 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004420}
4421
Anders Carlsson36760332007-10-15 20:28:48 +00004422Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4423 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004424 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004425 Expr *E = static_cast<Expr*>(expr);
4426 QualType T = QualType::getFromOpaquePtr(type);
4427
4428 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004429
4430 // Get the va_list type
4431 QualType VaListType = Context.getBuiltinVaListType();
4432 // Deal with implicit array decay; for example, on x86-64,
4433 // va_list is an array, but it's supposed to decay to
4434 // a pointer for va_arg.
4435 if (VaListType->isArrayType())
4436 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004437 // Make sure the input expression also decays appropriately.
4438 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004439
4440 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004441 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004442 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004443 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004444
4445 // FIXME: Warn if a non-POD type is passed in.
4446
Steve Naroff774e4152009-01-21 00:14:39 +00004447 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004448}
4449
Douglas Gregorad4b3792008-11-29 04:51:27 +00004450Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4451 // The type of __null will be int or long, depending on the size of
4452 // pointers on the target.
4453 QualType Ty;
4454 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4455 Ty = Context.IntTy;
4456 else
4457 Ty = Context.LongTy;
4458
Steve Naroff774e4152009-01-21 00:14:39 +00004459 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004460}
4461
Chris Lattner005ed752008-01-04 18:04:52 +00004462bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4463 SourceLocation Loc,
4464 QualType DstType, QualType SrcType,
4465 Expr *SrcExpr, const char *Flavor) {
4466 // Decode the result (notice that AST's are still created for extensions).
4467 bool isInvalid = false;
4468 unsigned DiagKind;
4469 switch (ConvTy) {
4470 default: assert(0 && "Unknown conversion type");
4471 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004472 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004473 DiagKind = diag::ext_typecheck_convert_pointer_int;
4474 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004475 case IntToPointer:
4476 DiagKind = diag::ext_typecheck_convert_int_pointer;
4477 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004478 case IncompatiblePointer:
4479 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4480 break;
4481 case FunctionVoidPointer:
4482 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4483 break;
4484 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004485 // If the qualifiers lost were because we were applying the
4486 // (deprecated) C++ conversion from a string literal to a char*
4487 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4488 // Ideally, this check would be performed in
4489 // CheckPointerTypesForAssignment. However, that would require a
4490 // bit of refactoring (so that the second argument is an
4491 // expression, rather than a type), which should be done as part
4492 // of a larger effort to fix CheckPointerTypesForAssignment for
4493 // C++ semantics.
4494 if (getLangOptions().CPlusPlus &&
4495 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4496 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004497 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4498 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004499 case IntToBlockPointer:
4500 DiagKind = diag::err_int_to_block_pointer;
4501 break;
4502 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004503 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004504 break;
Steve Naroff19608432008-10-14 22:18:38 +00004505 case IncompatibleObjCQualifiedId:
4506 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4507 // it can give a more specific diagnostic.
4508 DiagKind = diag::warn_incompatible_qualified_id;
4509 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004510 case IncompatibleVectors:
4511 DiagKind = diag::warn_incompatible_vectors;
4512 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004513 case Incompatible:
4514 DiagKind = diag::err_typecheck_convert_incompatible;
4515 isInvalid = true;
4516 break;
4517 }
4518
Chris Lattner271d4c22008-11-24 05:29:24 +00004519 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4520 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004521 return isInvalid;
4522}
Anders Carlssond5201b92008-11-30 19:50:32 +00004523
4524bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4525{
4526 Expr::EvalResult EvalResult;
4527
4528 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4529 EvalResult.HasSideEffects) {
4530 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4531
4532 if (EvalResult.Diag) {
4533 // We only show the note if it's not the usual "invalid subexpression"
4534 // or if it's actually in a subexpression.
4535 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4536 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4537 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4538 }
4539
4540 return true;
4541 }
4542
4543 if (EvalResult.Diag) {
4544 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4545 E->getSourceRange();
4546
4547 // Print the reason it's not a constant.
4548 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4549 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4550 }
4551
4552 if (Result)
4553 *Result = EvalResult.Val.getInt();
4554 return false;
4555}