blob: 66f33c1ea2403f1a31f4d8ed608634fe633544c2 [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 Lattnerc72d22d2008-03-31 00:36:02 +0000603 // FIXME: This should use a new expr for a direct reference, don't turn
604 // this into Self->ivar, just return a BareIVarExpr or something.
605 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000606 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000607 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
608 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000610 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000611 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000612 }
613 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000614 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000615 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000616 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000617 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000618 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000619 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000620 }
Chris Lattner4b009652007-07-25 00:24:17 +0000621 if (D == 0) {
622 // Otherwise, this could be an implicitly declared function reference (legal
623 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000624 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000625 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000626 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 else {
628 // If this name wasn't predeclared and if this is not a function call,
629 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000630 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000631 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
632 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000633 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
634 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000635 return ExprError(Diag(Loc, diag::err_undeclared_use)
636 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000637 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000638 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000639 }
640 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000641
Sebastian Redl0c9da212009-02-03 20:19:35 +0000642 // If this is an expression of the form &Class::member, don't build an
643 // implicit member ref, because we want a pointer to the member in general,
644 // not any specific instance's member.
645 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000646 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000647 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000648 QualType DType;
649 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
650 DType = FD->getType().getNonReferenceType();
651 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
652 DType = Method->getType();
653 } else if (isa<OverloadedFunctionDecl>(D)) {
654 DType = Context.OverloadTy;
655 }
656 // Could be an inner type. That's diagnosed below, so ignore it here.
657 if (!DType.isNull()) {
658 // The pointer is type- and value-dependent if it points into something
659 // dependent.
660 bool Dependent = false;
661 for (; DC; DC = DC->getParent()) {
662 // FIXME: could stop early at namespace scope.
663 if (DC->isRecord()) {
664 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
665 if (Context.getTypeDeclType(Record)->isDependentType()) {
666 Dependent = true;
667 break;
668 }
669 }
670 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000671 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000672 }
673 }
674 }
675
Douglas Gregor723d3332009-01-07 00:43:41 +0000676 // We may have found a field within an anonymous union or struct
677 // (C++ [class.union]).
678 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
679 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
680 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000681
Douglas Gregor3257fb52008-12-22 05:46:06 +0000682 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
683 if (!MD->isStatic()) {
684 // C++ [class.mfct.nonstatic]p2:
685 // [...] if name lookup (3.4.1) resolves the name in the
686 // id-expression to a nonstatic nontype member of class X or of
687 // a base class of X, the id-expression is transformed into a
688 // class member access expression (5.2.5) using (*this) (9.3.2)
689 // as the postfix-expression to the left of the '.' operator.
690 DeclContext *Ctx = 0;
691 QualType MemberType;
692 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
693 Ctx = FD->getDeclContext();
694 MemberType = FD->getType();
695
696 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
697 MemberType = RefType->getPointeeType();
698 else if (!FD->isMutable()) {
699 unsigned combinedQualifiers
700 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
701 MemberType = MemberType.getQualifiedType(combinedQualifiers);
702 }
703 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
704 if (!Method->isStatic()) {
705 Ctx = Method->getParent();
706 MemberType = Method->getType();
707 }
708 } else if (OverloadedFunctionDecl *Ovl
709 = dyn_cast<OverloadedFunctionDecl>(D)) {
710 for (OverloadedFunctionDecl::function_iterator
711 Func = Ovl->function_begin(),
712 FuncEnd = Ovl->function_end();
713 Func != FuncEnd; ++Func) {
714 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
715 if (!DMethod->isStatic()) {
716 Ctx = Ovl->getDeclContext();
717 MemberType = Context.OverloadTy;
718 break;
719 }
720 }
721 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000722
723 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000724 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
725 QualType ThisType = Context.getTagDeclType(MD->getParent());
726 if ((Context.getCanonicalType(CtxType)
727 == Context.getCanonicalType(ThisType)) ||
728 IsDerivedFrom(ThisType, CtxType)) {
729 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000730 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000731 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000732 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000734 }
735 }
736 }
737 }
738
Douglas Gregor8acb7272008-12-11 16:49:14 +0000739 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000740 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
741 if (MD->isStatic())
742 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000743 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
744 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000745 }
746
Douglas Gregor3257fb52008-12-22 05:46:06 +0000747 // Any other ways we could have found the field in a well-formed
748 // program would have been turned into implicit member expressions
749 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000750 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
751 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000752 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000753
Chris Lattner4b009652007-07-25 00:24:17 +0000754 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000755 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000756 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000757 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000758 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000759 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000760
Steve Naroffd6163f32008-09-05 22:11:13 +0000761 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000762 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000763 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
764 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000765 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
766 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
767 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000768 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000769
Chris Lattnerd9037472009-02-15 01:38:09 +0000770 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner2cb744b2009-02-15 22:43:40 +0000771 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattnerd9037472009-02-15 01:38:09 +0000772
Douglas Gregor48840c72008-12-10 23:01:14 +0000773 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
774 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
775 Scope *CheckS = S;
776 while (CheckS) {
777 if (CheckS->isWithinElse() &&
778 CheckS->getControlParent()->isDeclScope(Var)) {
779 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000780 ExprError(Diag(Loc, diag::warn_value_always_false)
781 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000782 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000783 ExprError(Diag(Loc, diag::warn_value_always_zero)
784 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000785 break;
786 }
787
788 // Move up one more control parent to check again.
789 CheckS = CheckS->getControlParent();
790 if (CheckS)
791 CheckS = CheckS->getParent();
792 }
793 }
794 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000795
796 // Only create DeclRefExpr's for valid Decl's.
797 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000798 return ExprError();
799
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000800 // If the identifier reference is inside a block, and it refers to a value
801 // that is outside the block, create a BlockDeclRefExpr instead of a
802 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
803 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000804 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000805 // We do not do this for things like enum constants, global variables, etc,
806 // as they do not get snapshotted.
807 //
808 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000809 // The BlocksAttr indicates the variable is bound by-reference.
810 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000811 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000812 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000813
Steve Naroff52059382008-10-10 01:28:17 +0000814 // Variable will be bound by-copy, make it const within the closure.
815 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000816 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000817 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000818 }
819 // If this reference is not in a block or if the referenced variable is
820 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000821
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000822 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000823 bool ValueDependent = false;
824 if (getLangOptions().CPlusPlus) {
825 // C++ [temp.dep.expr]p3:
826 // An id-expression is type-dependent if it contains:
827 // - an identifier that was declared with a dependent type,
828 if (VD->getType()->isDependentType())
829 TypeDependent = true;
830 // - FIXME: a template-id that is dependent,
831 // - a conversion-function-id that specifies a dependent type,
832 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
833 Name.getCXXNameType()->isDependentType())
834 TypeDependent = true;
835 // - a nested-name-specifier that contains a class-name that
836 // names a dependent type.
837 else if (SS && !SS->isEmpty()) {
838 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
839 DC; DC = DC->getParent()) {
840 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000841 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000842 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
843 if (Context.getTypeDeclType(Record)->isDependentType()) {
844 TypeDependent = true;
845 break;
846 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000847 }
848 }
849 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000850
Douglas Gregora5d84612008-12-10 20:57:37 +0000851 // C++ [temp.dep.constexpr]p2:
852 //
853 // An identifier is value-dependent if it is:
854 // - a name declared with a dependent type,
855 if (TypeDependent)
856 ValueDependent = true;
857 // - the name of a non-type template parameter,
858 else if (isa<NonTypeTemplateParmDecl>(VD))
859 ValueDependent = true;
860 // - a constant with integral or enumeration type and is
861 // initialized with an expression that is value-dependent
862 // (FIXME!).
863 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000864
Sebastian Redlcd883f72009-01-18 18:53:16 +0000865 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
866 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000867}
868
Sebastian Redlcd883f72009-01-18 18:53:16 +0000869Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
870 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000871 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000872
Chris Lattner4b009652007-07-25 00:24:17 +0000873 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000874 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000875 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
876 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
877 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000878 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000879
Chris Lattner7e637512008-01-12 08:14:25 +0000880 // Pre-defined identifiers are of type char[x], where x is the length of the
881 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000882 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000883 if (FunctionDecl *FD = getCurFunctionDecl())
884 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000885 else if (ObjCMethodDecl *MD = getCurMethodDecl())
886 Length = MD->getSynthesizedMethodSize();
887 else {
888 Diag(Loc, diag::ext_predef_outside_function);
889 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
890 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
891 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892
893
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000894 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000895 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000896 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000897 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000898}
899
Sebastian Redlcd883f72009-01-18 18:53:16 +0000900Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000901 llvm::SmallString<16> CharBuffer;
902 CharBuffer.resize(Tok.getLength());
903 const char *ThisTokBegin = &CharBuffer[0];
904 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000905
Chris Lattner4b009652007-07-25 00:24:17 +0000906 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
907 Tok.getLocation(), PP);
908 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000909 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000910
911 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
912
Sebastian Redl75324932009-01-20 22:23:13 +0000913 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
914 Literal.isWide(),
915 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000916}
917
Sebastian Redlcd883f72009-01-18 18:53:16 +0000918Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
919 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000920 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
921 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000922 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000923 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000924 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000925 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000926 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000927
Chris Lattner4b009652007-07-25 00:24:17 +0000928 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000929 // Add padding so that NumericLiteralParser can overread by one character.
930 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000931 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000932
Chris Lattner4b009652007-07-25 00:24:17 +0000933 // Get the spelling of the token, which eliminates trigraphs, etc.
934 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000935
Chris Lattner4b009652007-07-25 00:24:17 +0000936 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
937 Tok.getLocation(), PP);
938 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000939 return ExprError();
940
Chris Lattner1de66eb2007-08-26 03:42:43 +0000941 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000942
Chris Lattner1de66eb2007-08-26 03:42:43 +0000943 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000944 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000945 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000946 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000947 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000948 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000949 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000950 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000951
952 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
953
Ted Kremenekddedbe22007-11-29 00:56:49 +0000954 // isExact will be set by GetFloatValue().
955 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000956 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
957 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000958
Chris Lattner1de66eb2007-08-26 03:42:43 +0000959 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000960 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000961 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000962 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000963
Neil Booth7421e9c2007-08-29 22:00:19 +0000964 // long long is a C99 feature.
965 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000966 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000967 Diag(Tok.getLocation(), diag::ext_longlong);
968
Chris Lattner4b009652007-07-25 00:24:17 +0000969 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000970 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971
Chris Lattner4b009652007-07-25 00:24:17 +0000972 if (Literal.GetIntegerValue(ResultVal)) {
973 // If this value didn't fit into uintmax_t, warn and force to ull.
974 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000975 Ty = Context.UnsignedLongLongTy;
976 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000977 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000978 } else {
979 // If this value fits into a ULL, try to figure out what else it fits into
980 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000981
Chris Lattner4b009652007-07-25 00:24:17 +0000982 // Octal, Hexadecimal, and integers with a U suffix are allowed to
983 // be an unsigned int.
984 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
985
986 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000987 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000988 if (!Literal.isLong && !Literal.isLongLong) {
989 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000990 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000991
Chris Lattner4b009652007-07-25 00:24:17 +0000992 // Does it fit in a unsigned int?
993 if (ResultVal.isIntN(IntSize)) {
994 // Does it fit in a signed int?
995 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000996 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000997 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000998 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000999 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
Chris Lattner4b009652007-07-25 00:24:17 +00001001 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001002
Chris Lattner4b009652007-07-25 00:24:17 +00001003 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001004 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001005 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001006
Chris Lattner4b009652007-07-25 00:24:17 +00001007 // Does it fit in a unsigned long?
1008 if (ResultVal.isIntN(LongSize)) {
1009 // Does it fit in a signed long?
1010 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001011 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001012 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001013 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001014 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001015 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016 }
1017
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001019 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001020 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001021
Chris Lattner4b009652007-07-25 00:24:17 +00001022 // Does it fit in a unsigned long long?
1023 if (ResultVal.isIntN(LongLongSize)) {
1024 // Does it fit in a signed long long?
1025 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001026 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001027 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001028 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001029 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001030 }
1031 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032
Chris Lattner4b009652007-07-25 00:24:17 +00001033 // If we still couldn't decide a type, we probably have something that
1034 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001035 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001036 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001037 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001038 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001039 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040
Chris Lattnere4068872008-05-09 05:59:00 +00001041 if (ResultVal.getBitWidth() != Width)
1042 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001043 }
Sebastian Redl75324932009-01-20 22:23:13 +00001044 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001045 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046
Chris Lattner1de66eb2007-08-26 03:42:43 +00001047 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1048 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001049 Res = new (Context) ImaginaryLiteral(Res,
1050 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001051
1052 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001053}
1054
Sebastian Redlcd883f72009-01-18 18:53:16 +00001055Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1056 SourceLocation R, ExprArg Val) {
1057 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001058 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001059 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001060}
1061
1062/// The UsualUnaryConversions() function is *not* called by this routine.
1063/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001064bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1065 SourceLocation OpLoc,
1066 const SourceRange &ExprRange,
1067 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001068 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001069 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001070 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001071 if (isSizeof)
1072 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1073 return false;
1074 }
1075
1076 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001077 Diag(OpLoc, diag::ext_sizeof_void_type)
1078 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001079 return false;
1080 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001081
Chris Lattner159fe082009-01-24 19:46:37 +00001082 return DiagnoseIncompleteType(OpLoc, exprType,
1083 isSizeof ? diag::err_sizeof_incomplete_type :
1084 diag::err_alignof_incomplete_type,
1085 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001086}
1087
Chris Lattner8d9f7962009-01-24 20:17:12 +00001088bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1089 const SourceRange &ExprRange) {
1090 E = E->IgnoreParens();
1091
1092 // alignof decl is always ok.
1093 if (isa<DeclRefExpr>(E))
1094 return false;
1095
1096 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1097 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1098 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001099 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001100 return true;
1101 }
1102 // Other fields are ok.
1103 return false;
1104 }
1105 }
1106 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1107}
1108
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001109/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1110/// the same for @c alignof and @c __alignof
1111/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001112Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001113Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1114 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001115 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001116 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001117
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001118 QualType ArgTy;
1119 SourceRange Range;
1120 if (isType) {
1121 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1122 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001123
1124 // Verify that the operand is valid.
1125 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1126 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001127 } else {
1128 // Get the end location.
1129 Expr *ArgEx = (Expr *)TyOrEx;
1130 Range = ArgEx->getSourceRange();
1131 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001132
1133 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001134 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001135 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001136 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001137 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1138 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1139 isInvalid = true;
1140 } else {
1141 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1142 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001143
1144 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001145 DeleteExpr(ArgEx);
1146 return ExprError();
1147 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001148 }
1149
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001150 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001151 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001152 Context.getSizeType(), OpLoc,
1153 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001154}
1155
Chris Lattner5110ad52007-08-24 21:41:10 +00001156QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001157 DefaultFunctionArrayConversion(V);
1158
Chris Lattnera16e42d2007-08-26 05:39:26 +00001159 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001160 if (const ComplexType *CT = V->getType()->getAsComplexType())
1161 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001162
1163 // Otherwise they pass through real integer and floating point types here.
1164 if (V->getType()->isArithmeticType())
1165 return V->getType();
1166
1167 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001168 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001169 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001170}
1171
1172
Chris Lattner4b009652007-07-25 00:24:17 +00001173
Sebastian Redl8b769972009-01-19 00:08:26 +00001174Action::OwningExprResult
1175Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1176 tok::TokenKind Kind, ExprArg Input) {
1177 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001178
Chris Lattner4b009652007-07-25 00:24:17 +00001179 UnaryOperator::Opcode Opc;
1180 switch (Kind) {
1181 default: assert(0 && "Unknown unary op!");
1182 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1183 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1184 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001185
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001186 if (getLangOptions().CPlusPlus &&
1187 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1188 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001189 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001190 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1191
1192 // C++ [over.inc]p1:
1193 //
1194 // [...] If the function is a member function with one
1195 // parameter (which shall be of type int) or a non-member
1196 // function with two parameters (the second of which shall be
1197 // of type int), it defines the postfix increment operator ++
1198 // for objects of that type. When the postfix increment is
1199 // called as a result of using the ++ operator, the int
1200 // argument will have value zero.
1201 Expr *Args[2] = {
1202 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001203 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1204 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001205 };
1206
1207 // Build the candidate set for overloading
1208 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001209 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1210 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001211
1212 // Perform overload resolution.
1213 OverloadCandidateSet::iterator Best;
1214 switch (BestViableFunction(CandidateSet, Best)) {
1215 case OR_Success: {
1216 // We found a built-in operator or an overloaded operator.
1217 FunctionDecl *FnDecl = Best->Function;
1218
1219 if (FnDecl) {
1220 // We matched an overloaded operator. Build a call to that
1221 // operator.
1222
1223 // Convert the arguments.
1224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1225 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001226 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001227 } else {
1228 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001229 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001230 FnDecl->getParamDecl(0)->getType(),
1231 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001232 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001233 }
1234
1235 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001236 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001237 = FnDecl->getType()->getAsFunctionType()->getResultType();
1238 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001239
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001240 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001241 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001242 SourceLocation());
1243 UsualUnaryConversions(FnExpr);
1244
Sebastian Redl8b769972009-01-19 00:08:26 +00001245 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001246 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1247 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001248 } else {
1249 // We matched a built-in operator. Convert the arguments, then
1250 // break out so that we will build the appropriate built-in
1251 // operator node.
1252 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1253 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001254 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001255
1256 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001257 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001258 }
1259
1260 case OR_No_Viable_Function:
1261 // No viable function; fall through to handling this as a
1262 // built-in operator, which will produce an error message for us.
1263 break;
1264
1265 case OR_Ambiguous:
1266 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1267 << UnaryOperator::getOpcodeStr(Opc)
1268 << Arg->getSourceRange();
1269 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001270 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001271 }
1272
1273 // Either we found no viable overloaded operator or we matched a
1274 // built-in operator. In either case, fall through to trying to
1275 // build a built-in operation.
1276 }
1277
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001278 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1279 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001280 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001281 return ExprError();
1282 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001283 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001284}
1285
Sebastian Redl8b769972009-01-19 00:08:26 +00001286Action::OwningExprResult
1287Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1288 ExprArg Idx, SourceLocation RLoc) {
1289 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1290 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001291
Douglas Gregor80723c52008-11-19 17:17:41 +00001292 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001293 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001294 LHSExp->getType()->isEnumeralType() ||
1295 RHSExp->getType()->isRecordType() ||
1296 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001297 // Add the appropriate overloaded operators (C++ [over.match.oper])
1298 // to the candidate set.
1299 OverloadCandidateSet CandidateSet;
1300 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001301 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1302 SourceRange(LLoc, RLoc)))
1303 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001304
Douglas Gregor80723c52008-11-19 17:17:41 +00001305 // Perform overload resolution.
1306 OverloadCandidateSet::iterator Best;
1307 switch (BestViableFunction(CandidateSet, Best)) {
1308 case OR_Success: {
1309 // We found a built-in operator or an overloaded operator.
1310 FunctionDecl *FnDecl = Best->Function;
1311
1312 if (FnDecl) {
1313 // We matched an overloaded operator. Build a call to that
1314 // operator.
1315
1316 // Convert the arguments.
1317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1318 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1319 PerformCopyInitialization(RHSExp,
1320 FnDecl->getParamDecl(0)->getType(),
1321 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001322 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001323 } else {
1324 // Convert the arguments.
1325 if (PerformCopyInitialization(LHSExp,
1326 FnDecl->getParamDecl(0)->getType(),
1327 "passing") ||
1328 PerformCopyInitialization(RHSExp,
1329 FnDecl->getParamDecl(1)->getType(),
1330 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001331 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001332 }
1333
1334 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001335 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001336 = FnDecl->getType()->getAsFunctionType()->getResultType();
1337 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001338
Douglas Gregor80723c52008-11-19 17:17:41 +00001339 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001340 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001341 SourceLocation());
1342 UsualUnaryConversions(FnExpr);
1343
Sebastian Redl8b769972009-01-19 00:08:26 +00001344 Base.release();
1345 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001346 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001347 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001348 } else {
1349 // We matched a built-in operator. Convert the arguments, then
1350 // break out so that we will build the appropriate built-in
1351 // operator node.
1352 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1353 "passing") ||
1354 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1355 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001356 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001357
1358 break;
1359 }
1360 }
1361
1362 case OR_No_Viable_Function:
1363 // No viable function; fall through to handling this as a
1364 // built-in operator, which will produce an error message for us.
1365 break;
1366
1367 case OR_Ambiguous:
1368 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1369 << "[]"
1370 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1371 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001372 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001373 }
1374
1375 // Either we found no viable overloaded operator or we matched a
1376 // built-in operator. In either case, fall through to trying to
1377 // build a built-in operation.
1378 }
1379
Chris Lattner4b009652007-07-25 00:24:17 +00001380 // Perform default conversions.
1381 DefaultFunctionArrayConversion(LHSExp);
1382 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001383
Chris Lattner4b009652007-07-25 00:24:17 +00001384 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1385
1386 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001387 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001388 // in the subscript position. As a result, we need to derive the array base
1389 // and index from the expression types.
1390 Expr *BaseExpr, *IndexExpr;
1391 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001392 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001393 BaseExpr = LHSExp;
1394 IndexExpr = RHSExp;
1395 // FIXME: need to deal with const...
1396 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001397 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001398 // Handle the uncommon case of "123[Ptr]".
1399 BaseExpr = RHSExp;
1400 IndexExpr = LHSExp;
1401 // FIXME: need to deal with const...
1402 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001403 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1404 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001405 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001406
Chris Lattner4b009652007-07-25 00:24:17 +00001407 // FIXME: need to deal with const...
1408 ResultType = VTy->getElementType();
1409 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001410 return ExprError(Diag(LHSExp->getLocStart(),
1411 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1412 }
Chris Lattner4b009652007-07-25 00:24:17 +00001413 // C99 6.5.2.1p1
1414 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001415 return ExprError(Diag(IndexExpr->getLocStart(),
1416 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001417
1418 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1419 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001420 // void (*)(int)) and pointers to incomplete types. Functions are not
1421 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001422 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001423 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001424 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001425 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001426
Sebastian Redl8b769972009-01-19 00:08:26 +00001427 Base.release();
1428 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001429 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1430 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001431}
1432
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001433QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001434CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001435 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001436 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001437
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001438 // The vector accessor can't exceed the number of elements.
1439 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001440
1441 // This flag determines whether or not the component is one of the four
1442 // special names that indicate a subset of exactly half the elements are
1443 // to be selected.
1444 bool HalvingSwizzle = false;
1445
1446 // This flag determines whether or not CompName has an 's' char prefix,
1447 // indicating that it is a string of hex values to be used as vector indices.
1448 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001449
1450 // Check that we've found one of the special components, or that the component
1451 // names must come from the same set.
1452 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001453 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1454 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001455 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001456 do
1457 compStr++;
1458 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001459 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001460 do
1461 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001462 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001463 }
Nate Begeman1486b502009-01-18 01:47:54 +00001464
1465 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001466 // We didn't get to the end of the string. This means the component names
1467 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001468 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1469 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001470 return QualType();
1471 }
Nate Begeman1486b502009-01-18 01:47:54 +00001472
1473 // Ensure no component accessor exceeds the width of the vector type it
1474 // operates on.
1475 if (!HalvingSwizzle) {
1476 compStr = CompName.getName();
1477
1478 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001479 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001480
1481 while (*compStr) {
1482 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1483 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1484 << baseType << SourceRange(CompLoc);
1485 return QualType();
1486 }
1487 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001488 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001489
Nate Begeman1486b502009-01-18 01:47:54 +00001490 // If this is a halving swizzle, verify that the base type has an even
1491 // number of elements.
1492 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001493 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001494 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001495 return QualType();
1496 }
1497
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001498 // The component accessor looks fine - now we need to compute the actual type.
1499 // The vector type is implied by the component accessor. For example,
1500 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001501 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001502 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001503 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1504 : CompName.getLength();
1505 if (HexSwizzle)
1506 CompSize--;
1507
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001508 if (CompSize == 1)
1509 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001510
Nate Begemanaf6ed502008-04-18 23:10:10 +00001511 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001512 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001513 // diagostics look bad. We want extended vector types to appear built-in.
1514 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1515 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1516 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001517 }
1518 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001519}
1520
Chris Lattner2cb744b2009-02-15 22:43:40 +00001521
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001522/// constructSetterName - Return the setter name for the given
1523/// identifier, i.e. "set" + Name where the initial character of Name
1524/// has been capitalized.
1525// FIXME: Merge with same routine in Parser. But where should this
1526// live?
1527static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1528 const IdentifierInfo *Name) {
1529 llvm::SmallString<100> SelectorName;
1530 SelectorName = "set";
1531 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1532 SelectorName[3] = toupper(SelectorName[3]);
1533 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1534}
1535
Sebastian Redl8b769972009-01-19 00:08:26 +00001536Action::OwningExprResult
1537Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1538 tok::TokenKind OpKind, SourceLocation MemberLoc,
1539 IdentifierInfo &Member) {
1540 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001541 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001542
1543 // Perform default conversions.
1544 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001545
Steve Naroff2cb66382007-07-26 03:11:44 +00001546 QualType BaseType = BaseExpr->getType();
1547 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001548
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001549 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1550 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001551 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001552 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001553 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001554 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001555 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1556 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001557 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001558 return ExprError(Diag(MemberLoc,
1559 diag::err_typecheck_member_reference_arrow)
1560 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001561 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001562
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001563 // Handle field access to simple records. This also handles access to fields
1564 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001565 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001566 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001567 if (DiagnoseIncompleteType(OpLoc, BaseType,
1568 diag::err_typecheck_incomplete_tag,
1569 BaseExpr->getSourceRange()))
1570 return ExprError();
1571
Steve Naroff2cb66382007-07-26 03:11:44 +00001572 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001573 // FIXME: Qualified name lookup for C++ is a bit more complicated
1574 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001575 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001576 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001577 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001578
Douglas Gregor09be81b2009-02-04 17:27:36 +00001579 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001580 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001581 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1582 << &Member << BaseExpr->getSourceRange());
1583 else if (Result.isAmbiguous()) {
1584 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1585 MemberLoc, BaseExpr->getSourceRange());
1586 return ExprError();
1587 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001588 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001589
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001590 // If the decl being referenced had an error, return an error for this
1591 // sub-expr without emitting another error, in order to avoid cascading
1592 // error cases.
1593 if (MemberDecl->isInvalidDecl())
1594 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001595
1596 // Check if referencing a field with __attribute__((deprecated)).
1597 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001598
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001599 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001600 // We may have found a field within an anonymous union or struct
1601 // (C++ [class.union]).
1602 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001603 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001604 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001605
Douglas Gregor82d44772008-12-20 23:49:58 +00001606 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1607 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001608 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001609 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1610 MemberType = Ref->getPointeeType();
1611 else {
1612 unsigned combinedQualifiers =
1613 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001614 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001615 combinedQualifiers &= ~QualType::Const;
1616 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1617 }
Eli Friedman76b49832008-02-06 22:48:16 +00001618
Steve Naroff774e4152009-01-21 00:14:39 +00001619 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1620 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001621 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001622 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001623 Var, MemberLoc,
1624 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001625 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001626 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1627 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001628 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001629 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001630 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001631 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001632 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001633 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001634 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001635 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001636 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1637 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001638
Douglas Gregor82d44772008-12-20 23:49:58 +00001639 // We found a declaration kind that we didn't expect. This is a
1640 // generic error message that tells the user that she can't refer
1641 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001642 return ExprError(Diag(MemberLoc,
1643 diag::err_typecheck_member_reference_unknown)
1644 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001645 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001646
Chris Lattnere9d71612008-07-21 04:59:05 +00001647 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1648 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001649 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001650 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001651 // If the decl being referenced had an error, return an error for this
1652 // sub-expr without emitting another error, in order to avoid cascading
1653 // error cases.
1654 if (IV->isInvalidDecl())
1655 return ExprError();
1656
Steve Naroff774e4152009-01-21 00:14:39 +00001657 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1658 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001659 OpKind == tok::arrow);
1660 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001661 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001662 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001663 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1664 << IFTy->getDecl()->getDeclName() << &Member
1665 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001666 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001667
Chris Lattnere9d71612008-07-21 04:59:05 +00001668 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1669 // pointer to a (potentially qualified) interface type.
1670 const PointerType *PTy;
1671 const ObjCInterfaceType *IFTy;
1672 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1673 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1674 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001675
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001676 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001677 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001678 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001679 MemberLoc, BaseExpr));
1680
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001681 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001682 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1683 E = IFTy->qual_end(); I != E; ++I)
1684 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001685 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001686 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001687
1688 // If that failed, look for an "implicit" property by seeing if the nullary
1689 // selector is implemented.
1690
1691 // FIXME: The logic for looking up nullary and unary selectors should be
1692 // shared with the code in ActOnInstanceMessage.
1693
1694 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1695 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001696
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001697 // If this reference is in an @implementation, check for 'private' methods.
1698 if (!Getter)
1699 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1700 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1701 if (ObjCImplementationDecl *ImpDecl =
1702 ObjCImplementations[ClassDecl->getIdentifier()])
1703 Getter = ImpDecl->getInstanceMethod(Sel);
1704
Steve Naroff04151f32008-10-22 19:16:27 +00001705 // Look through local category implementations associated with the class.
1706 if (!Getter) {
1707 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1708 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1709 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1710 }
1711 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001712 if (Getter) {
1713 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001714 // will look for the matching setter, in case it is needed.
1715 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1716 &Member);
1717 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1718 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1719 if (!Setter) {
1720 // If this reference is in an @implementation, also check for 'private'
1721 // methods.
1722 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1723 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1724 if (ObjCImplementationDecl *ImpDecl =
1725 ObjCImplementations[ClassDecl->getIdentifier()])
1726 Setter = ImpDecl->getInstanceMethod(SetterSel);
1727 }
1728 // Look through local category implementations associated with the class.
1729 if (!Setter) {
1730 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1731 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1732 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1733 }
1734 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001735
1736 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001737 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1738 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001739 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001740
1741 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1742 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001743 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001744 // Handle properties on qualified "id" protocols.
1745 const ObjCQualifiedIdType *QIdTy;
1746 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1747 // Check protocols on qualified interfaces.
1748 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001749 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001750 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001751 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001752 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001753 // Also must look for a getter name which uses property syntax.
1754 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1755 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001756 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1757 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001758 }
1759 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001760
1761 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1762 << &Member << BaseType);
1763 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001764 // Handle 'field access' to vectors, such as 'V.xx'.
1765 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001766 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1767 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001768 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001769 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1770 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001771 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001772
1773 return ExprError(Diag(MemberLoc,
1774 diag::err_typecheck_member_reference_struct_union)
1775 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001776}
1777
Douglas Gregor3257fb52008-12-22 05:46:06 +00001778/// ConvertArgumentsForCall - Converts the arguments specified in
1779/// Args/NumArgs to the parameter types of the function FDecl with
1780/// function prototype Proto. Call is the call expression itself, and
1781/// Fn is the function expression. For a C++ member function, this
1782/// routine does not attempt to convert the object argument. Returns
1783/// true if the call is ill-formed.
1784bool
1785Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1786 FunctionDecl *FDecl,
1787 const FunctionTypeProto *Proto,
1788 Expr **Args, unsigned NumArgs,
1789 SourceLocation RParenLoc) {
1790 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1791 // assignment, to the types of the corresponding parameter, ...
1792 unsigned NumArgsInProto = Proto->getNumArgs();
1793 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001794 bool Invalid = false;
1795
Douglas Gregor3257fb52008-12-22 05:46:06 +00001796 // If too few arguments are available (and we don't have default
1797 // arguments for the remaining parameters), don't make the call.
1798 if (NumArgs < NumArgsInProto) {
1799 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1800 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1801 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1802 // Use default arguments for missing arguments
1803 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001804 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001805 }
1806
1807 // If too many are passed and not variadic, error on the extras and drop
1808 // them.
1809 if (NumArgs > NumArgsInProto) {
1810 if (!Proto->isVariadic()) {
1811 Diag(Args[NumArgsInProto]->getLocStart(),
1812 diag::err_typecheck_call_too_many_args)
1813 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1814 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1815 Args[NumArgs-1]->getLocEnd());
1816 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001817 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001818 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001819 }
1820 NumArgsToCheck = NumArgsInProto;
1821 }
1822
1823 // Continue to check argument types (even if we have too few/many args).
1824 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1825 QualType ProtoArgType = Proto->getArgType(i);
1826
1827 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001828 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001829 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001830
1831 // Pass the argument.
1832 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1833 return true;
1834 } else
1835 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001836 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001837 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001838
Douglas Gregor3257fb52008-12-22 05:46:06 +00001839 Call->setArg(i, Arg);
1840 }
1841
1842 // If this is a variadic call, handle args passed through "...".
1843 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001844 VariadicCallType CallType = VariadicFunction;
1845 if (Fn->getType()->isBlockPointerType())
1846 CallType = VariadicBlock; // Block
1847 else if (isa<MemberExpr>(Fn))
1848 CallType = VariadicMethod;
1849
Douglas Gregor3257fb52008-12-22 05:46:06 +00001850 // Promote the arguments (C99 6.5.2.2p7).
1851 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1852 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001853 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001854 Call->setArg(i, Arg);
1855 }
1856 }
1857
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001858 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001859}
1860
Steve Naroff87d58b42007-09-16 03:34:24 +00001861/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001862/// This provides the location of the left/right parens and a list of comma
1863/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001864Action::OwningExprResult
1865Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1866 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001867 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001868 unsigned NumArgs = args.size();
1869 Expr *Fn = static_cast<Expr *>(fn.release());
1870 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001871 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001872 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001873 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001874
Douglas Gregor3257fb52008-12-22 05:46:06 +00001875 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001876 // Determine whether this is a dependent call inside a C++ template,
1877 // in which case we won't do any semantic analysis now.
1878 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1879 bool Dependent = false;
1880 if (Fn->isTypeDependent())
1881 Dependent = true;
1882 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1883 Dependent = true;
1884
1885 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001886 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001887 Context.DependentTy, RParenLoc));
1888
1889 // Determine whether this is a call to an object (C++ [over.call.object]).
1890 if (Fn->getType()->isRecordType())
1891 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1892 CommaLocs, RParenLoc));
1893
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001894 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001895 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1896 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1897 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001898 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1899 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001900 }
1901
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001902 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001903 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001904 Expr *FnExpr = Fn;
1905 bool ADL = true;
1906 while (true) {
1907 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1908 FnExpr = IcExpr->getSubExpr();
1909 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001910 // Parentheses around a function disable ADL
1911 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001912 ADL = false;
1913 FnExpr = PExpr->getSubExpr();
1914 } else if (isa<UnaryOperator>(FnExpr) &&
1915 cast<UnaryOperator>(FnExpr)->getOpcode()
1916 == UnaryOperator::AddrOf) {
1917 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001918 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1919 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1920 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1921 break;
1922 } else if (UnresolvedFunctionNameExpr *DepName
1923 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1924 UnqualifiedName = DepName->getName();
1925 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001926 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001927 // Any kind of name that does not refer to a declaration (or
1928 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1929 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001930 break;
1931 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001932 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001933
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001934 OverloadedFunctionDecl *Ovl = 0;
1935 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001936 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001937 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1938 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001939
Douglas Gregorfcb19192009-02-11 23:02:49 +00001940 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001941 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001942 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001943 ADL = false;
1944
Douglas Gregorfcb19192009-02-11 23:02:49 +00001945 // We don't perform ADL in C.
1946 if (!getLangOptions().CPlusPlus)
1947 ADL = false;
1948
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001949 if (Ovl || ADL) {
1950 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1951 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001952 NumArgs, CommaLocs, RParenLoc, ADL);
1953 if (!FDecl)
1954 return ExprError();
1955
1956 // Update Fn to refer to the actual function selected.
1957 Expr *NewFn = 0;
1958 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001959 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001960 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1961 QDRExpr->getLocation(),
1962 false, false,
1963 QDRExpr->getSourceRange().getBegin());
1964 else
1965 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1966 Fn->getSourceRange().getBegin());
1967 Fn->Destroy(Context);
1968 Fn = NewFn;
1969 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001970 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001971
1972 // Promote the function operand.
1973 UsualUnaryConversions(Fn);
1974
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001975 // Make the call expr early, before semantic checks. This guarantees cleanup
1976 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001977 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1978 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00001979 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
1980 Args, NumArgs,
1981 Context.BoolTy,
1982 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001983
Steve Naroffd6163f32008-09-05 22:11:13 +00001984 const FunctionType *FuncT;
1985 if (!Fn->getType()->isBlockPointerType()) {
1986 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1987 // have type pointer to function".
1988 const PointerType *PT = Fn->getType()->getAsPointerType();
1989 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001990 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1991 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001992 FuncT = PT->getPointeeType()->getAsFunctionType();
1993 } else { // This is a block call.
1994 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1995 getAsFunctionType();
1996 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001997 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001998 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1999 << Fn->getType() << Fn->getSourceRange());
2000
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002001 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002002 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002003
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002004 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002005 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2006 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002007 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002008 } else {
2009 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002010
Steve Naroffdb65e052007-08-28 23:30:39 +00002011 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002012 for (unsigned i = 0; i != NumArgs; i++) {
2013 Expr *Arg = Args[i];
2014 DefaultArgumentPromotion(Arg);
2015 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002016 }
Chris Lattner4b009652007-07-25 00:24:17 +00002017 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002018
Douglas Gregor3257fb52008-12-22 05:46:06 +00002019 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2020 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002021 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2022 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002023
Chris Lattner2e64c072007-08-10 20:18:51 +00002024 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002025 if (FDecl)
2026 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002027
Sebastian Redl8b769972009-01-19 00:08:26 +00002028 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002029}
2030
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002031Action::OwningExprResult
2032Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2033 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002034 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002035 QualType literalType = QualType::getFromOpaquePtr(Ty);
2036 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002037 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002038 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002039
Eli Friedman8c2173d2008-05-20 05:22:08 +00002040 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002041 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002042 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2043 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002044 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2045 diag::err_typecheck_decl_incomplete_type,
2046 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002047 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002048
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002049 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002050 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002051 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002052
Chris Lattnere5cb5862008-12-04 23:50:19 +00002053 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002054 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002055 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002056 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002057 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002058 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002059 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2060 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002061}
2062
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002063Action::OwningExprResult
2064Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2065 InitListDesignations &Designators,
2066 SourceLocation RBraceLoc) {
2067 unsigned NumInit = initlist.size();
2068 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002069
Steve Naroff0acc9c92007-09-15 18:49:24 +00002070 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002071 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002072
Steve Naroff774e4152009-01-21 00:14:39 +00002073 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002074 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002075 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002076 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002077}
2078
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002079/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002080bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002081 UsualUnaryConversions(castExpr);
2082
2083 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2084 // type needs to be scalar.
2085 if (castType->isVoidType()) {
2086 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002087 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2088 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002089 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002090 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2091 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2092 (castType->isStructureType() || castType->isUnionType())) {
2093 // GCC struct/union extension: allow cast to self.
2094 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2095 << castType << castExpr->getSourceRange();
2096 } else if (castType->isUnionType()) {
2097 // GCC cast to union extension
2098 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2099 RecordDecl::field_iterator Field, FieldEnd;
2100 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2101 Field != FieldEnd; ++Field) {
2102 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2103 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2104 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2105 << castExpr->getSourceRange();
2106 break;
2107 }
2108 }
2109 if (Field == FieldEnd)
2110 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2111 << castExpr->getType() << castExpr->getSourceRange();
2112 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002113 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002114 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002115 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002116 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002117 } else if (!castExpr->getType()->isScalarType() &&
2118 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002119 return Diag(castExpr->getLocStart(),
2120 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002121 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002122 } else if (castExpr->getType()->isVectorType()) {
2123 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2124 return true;
2125 } else if (castType->isVectorType()) {
2126 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2127 return true;
2128 }
2129 return false;
2130}
2131
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002132bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002133 assert(VectorTy->isVectorType() && "Not a vector type!");
2134
2135 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002136 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002137 return Diag(R.getBegin(),
2138 Ty->isVectorType() ?
2139 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002140 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002141 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002142 } else
2143 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002144 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002145 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002146
2147 return false;
2148}
2149
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002150Action::OwningExprResult
2151Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2152 SourceLocation RParenLoc, ExprArg Op) {
2153 assert((Ty != 0) && (Op.get() != 0) &&
2154 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002155
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002156 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002157 QualType castType = QualType::getFromOpaquePtr(Ty);
2158
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002159 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002160 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002161 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002162 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002163}
2164
Chris Lattner98a425c2007-11-26 01:40:58 +00002165/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2166/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002167inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2168 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2169 UsualUnaryConversions(cond);
2170 UsualUnaryConversions(lex);
2171 UsualUnaryConversions(rex);
2172 QualType condT = cond->getType();
2173 QualType lexT = lex->getType();
2174 QualType rexT = rex->getType();
2175
2176 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002177 if (!cond->isTypeDependent()) {
2178 if (!condT->isScalarType()) { // C99 6.5.15p2
2179 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2180 return QualType();
2181 }
Chris Lattner4b009652007-07-25 00:24:17 +00002182 }
Chris Lattner992ae932008-01-06 22:42:25 +00002183
2184 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002185 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2186 return Context.DependentTy;
2187
Chris Lattner992ae932008-01-06 22:42:25 +00002188 // If both operands have arithmetic type, do the usual arithmetic conversions
2189 // to find a common type: C99 6.5.15p3,5.
2190 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002191 UsualArithmeticConversions(lex, rex);
2192 return lex->getType();
2193 }
Chris Lattner992ae932008-01-06 22:42:25 +00002194
2195 // If both operands are the same structure or union type, the result is that
2196 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002197 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002198 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002199 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002200 // "If both the operands have structure or union type, the result has
2201 // that type." This implies that CV qualifiers are dropped.
2202 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002203 }
Chris Lattner992ae932008-01-06 22:42:25 +00002204
2205 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002206 // The following || allows only one side to be void (a GCC-ism).
2207 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002208 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002209 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2210 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002211 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002212 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2213 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002214 ImpCastExprToType(lex, Context.VoidTy);
2215 ImpCastExprToType(rex, Context.VoidTy);
2216 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002217 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002218 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2219 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002220 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2221 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002222 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002223 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002224 return lexT;
2225 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002226 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2227 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002228 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002229 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002230 return rexT;
2231 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002232 // Handle the case where both operands are pointers before we handle null
2233 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002234 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2235 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2236 // get the "pointed to" types
2237 QualType lhptee = LHSPT->getPointeeType();
2238 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002239
Chris Lattner71225142007-07-31 21:27:01 +00002240 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2241 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002242 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002243 // Figure out necessary qualifiers (C99 6.5.15p6)
2244 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002245 QualType destType = Context.getPointerType(destPointee);
2246 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2247 ImpCastExprToType(rex, destType); // promote to void*
2248 return destType;
2249 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002250 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002251 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002252 QualType destType = Context.getPointerType(destPointee);
2253 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2254 ImpCastExprToType(rex, destType); // promote to void*
2255 return destType;
2256 }
Chris Lattner4b009652007-07-25 00:24:17 +00002257
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002258 QualType compositeType = lexT;
2259
2260 // If either type is an Objective-C object type then check
2261 // compatibility according to Objective-C.
2262 if (Context.isObjCObjectPointerType(lexT) ||
2263 Context.isObjCObjectPointerType(rexT)) {
2264 // If both operands are interfaces and either operand can be
2265 // assigned to the other, use that type as the composite
2266 // type. This allows
2267 // xxx ? (A*) a : (B*) b
2268 // where B is a subclass of A.
2269 //
2270 // Additionally, as for assignment, if either type is 'id'
2271 // allow silent coercion. Finally, if the types are
2272 // incompatible then make sure to use 'id' as the composite
2273 // type so the result is acceptable for sending messages to.
2274
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002275 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2276 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002277 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2278 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2279 if (LHSIface && RHSIface &&
2280 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2281 compositeType = lexT;
2282 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002283 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002284 compositeType = rexT;
Steve Naroff17c03822009-02-12 17:52:19 +00002285 } else if (Context.isObjCIdStructType(lhptee) ||
2286 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002287 compositeType = Context.getObjCIdType();
2288 } else {
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002289 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2290 << lexT << rexT
2291 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002292 QualType incompatTy = Context.getObjCIdType();
2293 ImpCastExprToType(lex, incompatTy);
2294 ImpCastExprToType(rex, incompatTy);
2295 return incompatTy;
2296 }
2297 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2298 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002299 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002300 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002301 // In this situation, we assume void* type. No especially good
2302 // reason, but this is what gcc does, and we do have to pick
2303 // to get a consistent AST.
2304 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002305 ImpCastExprToType(lex, incompatTy);
2306 ImpCastExprToType(rex, incompatTy);
2307 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002308 }
2309 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002310 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2311 // differently qualified versions of compatible types, the result type is
2312 // a pointer to an appropriately qualified version of the *composite*
2313 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002314 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002315 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002316 ImpCastExprToType(lex, compositeType);
2317 ImpCastExprToType(rex, compositeType);
2318 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002319 }
Chris Lattner4b009652007-07-25 00:24:17 +00002320 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002321 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2322 // evaluates to "struct objc_object *" (and is handled above when comparing
2323 // id with statically typed objects).
2324 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2325 // GCC allows qualified id and any Objective-C type to devolve to
2326 // id. Currently localizing to here until clear this should be
2327 // part of ObjCQualifiedIdTypesAreCompatible.
2328 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2329 (lexT->isObjCQualifiedIdType() &&
2330 Context.isObjCObjectPointerType(rexT)) ||
2331 (rexT->isObjCQualifiedIdType() &&
2332 Context.isObjCObjectPointerType(lexT))) {
2333 // FIXME: This is not the correct composite type. This only
2334 // happens to work because id can more or less be used anywhere,
2335 // however this may change the type of method sends.
2336 // FIXME: gcc adds some type-checking of the arguments and emits
2337 // (confusing) incompatible comparison warnings in some
2338 // cases. Investigate.
2339 QualType compositeType = Context.getObjCIdType();
2340 ImpCastExprToType(lex, compositeType);
2341 ImpCastExprToType(rex, compositeType);
2342 return compositeType;
2343 }
2344 }
2345
Steve Naroff3eac7692008-09-10 19:17:48 +00002346 // Selection between block pointer types is ok as long as they are the same.
2347 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2348 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2349 return lexT;
2350
Chris Lattner992ae932008-01-06 22:42:25 +00002351 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002352 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002353 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002354 return QualType();
2355}
2356
Steve Naroff87d58b42007-09-16 03:34:24 +00002357/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002358/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002359Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2360 SourceLocation ColonLoc,
2361 ExprArg Cond, ExprArg LHS,
2362 ExprArg RHS) {
2363 Expr *CondExpr = (Expr *) Cond.get();
2364 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002365
2366 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2367 // was the condition.
2368 bool isLHSNull = LHSExpr == 0;
2369 if (isLHSNull)
2370 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002371
2372 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002373 RHSExpr, QuestionLoc);
2374 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002375 return ExprError();
2376
2377 Cond.release();
2378 LHS.release();
2379 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002380 return Owned(new (Context) ConditionalOperator(CondExpr,
2381 isLHSNull ? 0 : LHSExpr,
2382 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002383}
2384
Chris Lattner4b009652007-07-25 00:24:17 +00002385
2386// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2387// being closely modeled after the C99 spec:-). The odd characteristic of this
2388// routine is it effectively iqnores the qualifiers on the top level pointee.
2389// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2390// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002391Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002392Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2393 QualType lhptee, rhptee;
2394
2395 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002396 lhptee = lhsType->getAsPointerType()->getPointeeType();
2397 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002398
2399 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002400 lhptee = Context.getCanonicalType(lhptee);
2401 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002402
Chris Lattner005ed752008-01-04 18:04:52 +00002403 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002404
2405 // C99 6.5.16.1p1: This following citation is common to constraints
2406 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2407 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002408 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002409 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002410 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002411
2412 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2413 // incomplete type and the other is a pointer to a qualified or unqualified
2414 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002415 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002416 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002417 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002418
2419 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002420 assert(rhptee->isFunctionType());
2421 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002422 }
2423
2424 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002425 if (lhptee->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(lhptee->isFunctionType());
2430 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002431 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002432
2433 // Check for ObjC interfaces
2434 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2435 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2436 if (LHSIface && RHSIface &&
2437 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2438 return ConvTy;
2439
2440 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002441 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002442 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002443 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002444 return ConvTy;
2445
Chris Lattner4b009652007-07-25 00:24:17 +00002446 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2447 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002448 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2449 rhptee.getUnqualifiedType()))
2450 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002451 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002452}
2453
Steve Naroff3454b6c2008-09-04 15:10:53 +00002454/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2455/// block pointer types are compatible or whether a block and normal pointer
2456/// are compatible. It is more restrict than comparing two function pointer
2457// types.
2458Sema::AssignConvertType
2459Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2460 QualType rhsType) {
2461 QualType lhptee, rhptee;
2462
2463 // get the "pointed to" type (ignoring qualifiers at the top level)
2464 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2465 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2466
2467 // make sure we operate on the canonical type
2468 lhptee = Context.getCanonicalType(lhptee);
2469 rhptee = Context.getCanonicalType(rhptee);
2470
2471 AssignConvertType ConvTy = Compatible;
2472
2473 // For blocks we enforce that qualifiers are identical.
2474 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2475 ConvTy = CompatiblePointerDiscardsQualifiers;
2476
2477 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2478 return IncompatibleBlockPointer;
2479 return ConvTy;
2480}
2481
Chris Lattner4b009652007-07-25 00:24:17 +00002482/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2483/// has code to accommodate several GCC extensions when type checking
2484/// pointers. Here are some objectionable examples that GCC considers warnings:
2485///
2486/// int a, *pint;
2487/// short *pshort;
2488/// struct foo *pfoo;
2489///
2490/// pint = pshort; // warning: assignment from incompatible pointer type
2491/// a = pint; // warning: assignment makes integer from pointer without a cast
2492/// pint = a; // warning: assignment makes pointer from integer without a cast
2493/// pint = pfoo; // warning: assignment from incompatible pointer type
2494///
2495/// As a result, the code for dealing with pointers is more complex than the
2496/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002497///
Chris Lattner005ed752008-01-04 18:04:52 +00002498Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002499Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002500 // Get canonical types. We're not formatting these types, just comparing
2501 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002502 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2503 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002504
2505 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002506 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002507
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002508 // If the left-hand side is a reference type, then we are in a
2509 // (rare!) case where we've allowed the use of references in C,
2510 // e.g., as a parameter type in a built-in function. In this case,
2511 // just make sure that the type referenced is compatible with the
2512 // right-hand side type. The caller is responsible for adjusting
2513 // lhsType so that the resulting expression does not have reference
2514 // type.
2515 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2516 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002517 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002518 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002519 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002520
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002521 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2522 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002523 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002524 // Relax integer conversions like we do for pointers below.
2525 if (rhsType->isIntegerType())
2526 return IntToPointer;
2527 if (lhsType->isIntegerType())
2528 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002529 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002530 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002531
Nate Begemanc5f0f652008-07-14 18:02:46 +00002532 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002533 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002534 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2535 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002536 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002537
Nate Begemanc5f0f652008-07-14 18:02:46 +00002538 // If we are allowing lax vector conversions, and LHS and RHS are both
2539 // vectors, the total size only needs to be the same. This is a bitcast;
2540 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002541 if (getLangOptions().LaxVectorConversions &&
2542 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002543 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002544 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002545 }
2546 return Incompatible;
2547 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002548
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002549 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002550 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002551
Chris Lattner390564e2008-04-07 06:49:41 +00002552 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002553 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002554 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002555
Chris Lattner390564e2008-04-07 06:49:41 +00002556 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002557 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002558
Steve Naroffa982c712008-09-29 18:10:17 +00002559 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002560 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002561 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002562
2563 // Treat block pointers as objects.
2564 if (getLangOptions().ObjC1 &&
2565 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2566 return Compatible;
2567 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002568 return Incompatible;
2569 }
2570
2571 if (isa<BlockPointerType>(lhsType)) {
2572 if (rhsType->isIntegerType())
2573 return IntToPointer;
2574
Steve Naroffa982c712008-09-29 18:10:17 +00002575 // Treat block pointers as objects.
2576 if (getLangOptions().ObjC1 &&
2577 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2578 return Compatible;
2579
Steve Naroff3454b6c2008-09-04 15:10:53 +00002580 if (rhsType->isBlockPointerType())
2581 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2582
2583 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2584 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002585 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002586 }
Chris Lattner1853da22008-01-04 23:18:45 +00002587 return Incompatible;
2588 }
2589
Chris Lattner390564e2008-04-07 06:49:41 +00002590 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002591 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002592 if (lhsType == Context.BoolTy)
2593 return Compatible;
2594
2595 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002596 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002597
Chris Lattner390564e2008-04-07 06:49:41 +00002598 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002599 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002600
2601 if (isa<BlockPointerType>(lhsType) &&
2602 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002603 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002604 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002605 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002606
Chris Lattner1853da22008-01-04 23:18:45 +00002607 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002608 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002609 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002610 }
2611 return Incompatible;
2612}
2613
Chris Lattner005ed752008-01-04 18:04:52 +00002614Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002615Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002616 if (getLangOptions().CPlusPlus) {
2617 if (!lhsType->isRecordType()) {
2618 // C++ 5.17p3: If the left operand is not of class type, the
2619 // expression is implicitly converted (C++ 4) to the
2620 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002621 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2622 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002623 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002624 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002625 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002626 }
2627
2628 // FIXME: Currently, we fall through and treat C++ classes like C
2629 // structures.
2630 }
2631
Steve Naroffcdee22d2007-11-27 17:58:44 +00002632 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2633 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002634 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2635 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002636 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002637 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002638 return Compatible;
2639 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002640
2641 // We don't allow conversion of non-null-pointer constants to integers.
2642 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2643 return IntToBlockPointer;
2644
Chris Lattner5f505bf2007-10-16 02:55:40 +00002645 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002646 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002647 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002648 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002649 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002650 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002651 if (!lhsType->isReferenceType())
2652 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002653
Chris Lattner005ed752008-01-04 18:04:52 +00002654 Sema::AssignConvertType result =
2655 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002656
2657 // C99 6.5.16.1p2: The value of the right operand is converted to the
2658 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002659 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2660 // so that we can use references in built-in functions even in C.
2661 // The getNonReferenceType() call makes sure that the resulting expression
2662 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002663 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002664 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002665 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002666}
2667
Chris Lattner005ed752008-01-04 18:04:52 +00002668Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002669Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2670 return CheckAssignmentConstraints(lhsType, rhsType);
2671}
2672
Chris Lattner1eafdea2008-11-18 01:30:42 +00002673QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002674 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002675 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002676 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002677 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002678}
2679
Chris Lattner1eafdea2008-11-18 01:30:42 +00002680inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002681 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002682 // For conversion purposes, we ignore any qualifiers.
2683 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002684 QualType lhsType =
2685 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2686 QualType rhsType =
2687 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002688
Nate Begemanc5f0f652008-07-14 18:02:46 +00002689 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002690 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002691 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002692
Nate Begemanc5f0f652008-07-14 18:02:46 +00002693 // Handle the case of a vector & extvector type of the same size and element
2694 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002695 if (getLangOptions().LaxVectorConversions) {
2696 // FIXME: Should we warn here?
2697 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002698 if (const VectorType *RV = rhsType->getAsVectorType())
2699 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002700 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002701 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002702 }
2703 }
2704 }
2705
Nate Begemanc5f0f652008-07-14 18:02:46 +00002706 // If the lhs is an extended vector and the rhs is a scalar of the same type
2707 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002708 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002709 QualType eltType = V->getElementType();
2710
2711 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2712 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2713 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002714 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002715 return lhsType;
2716 }
2717 }
2718
Nate Begemanc5f0f652008-07-14 18:02:46 +00002719 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002720 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002721 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002722 QualType eltType = V->getElementType();
2723
2724 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2725 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2726 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002727 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002728 return rhsType;
2729 }
2730 }
2731
Chris Lattner4b009652007-07-25 00:24:17 +00002732 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002733 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002734 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002735 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002736 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002737}
2738
Chris Lattner4b009652007-07-25 00:24:17 +00002739inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002740 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002741{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002742 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002743 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002744
Steve Naroff8f708362007-08-24 19:07:16 +00002745 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002746
Chris Lattner4b009652007-07-25 00:24:17 +00002747 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002748 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002749 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002750}
2751
2752inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002753 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002754{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002755 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2756 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2757 return CheckVectorOperands(Loc, lex, rex);
2758 return InvalidOperands(Loc, lex, rex);
2759 }
Chris Lattner4b009652007-07-25 00:24:17 +00002760
Steve Naroff8f708362007-08-24 19:07:16 +00002761 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002762
Chris Lattner4b009652007-07-25 00:24:17 +00002763 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002764 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002765 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002766}
2767
2768inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002769 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002770{
2771 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002772 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002773
Steve Naroff8f708362007-08-24 19:07:16 +00002774 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002775
Chris Lattner4b009652007-07-25 00:24:17 +00002776 // handle the common case first (both operands are arithmetic).
2777 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002778 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002779
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002780 // Put any potential pointer into PExp
2781 Expr* PExp = lex, *IExp = rex;
2782 if (IExp->getType()->isPointerType())
2783 std::swap(PExp, IExp);
2784
2785 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2786 if (IExp->getType()->isIntegerType()) {
2787 // Check for arithmetic on pointers to incomplete types
2788 if (!PTy->getPointeeType()->isObjectType()) {
2789 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002790 if (getLangOptions().CPlusPlus) {
2791 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2792 << lex->getSourceRange() << rex->getSourceRange();
2793 return QualType();
2794 }
2795
2796 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002797 Diag(Loc, diag::ext_gnu_void_ptr)
2798 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002799 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002800 if (getLangOptions().CPlusPlus) {
2801 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2802 << lex->getType() << lex->getSourceRange();
2803 return QualType();
2804 }
2805
2806 // GNU extension: arithmetic on pointer to function
2807 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002808 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002809 } else {
2810 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2811 diag::err_typecheck_arithmetic_incomplete_type,
2812 lex->getSourceRange(), SourceRange(),
2813 lex->getType());
2814 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002815 }
2816 }
2817 return PExp->getType();
2818 }
2819 }
2820
Chris Lattner1eafdea2008-11-18 01:30:42 +00002821 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002822}
2823
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002824// C99 6.5.6
2825QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002826 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002827 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002828 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002829
Steve Naroff8f708362007-08-24 19:07:16 +00002830 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002831
Chris Lattnerf6da2912007-12-09 21:53:25 +00002832 // Enforce type constraints: C99 6.5.6p3.
2833
2834 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002835 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002836 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002837
2838 // Either ptr - int or ptr - ptr.
2839 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002840 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002841
Chris Lattnerf6da2912007-12-09 21:53:25 +00002842 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002843 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002844 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002845 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002846 Diag(Loc, diag::ext_gnu_void_ptr)
2847 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002848 } else if (lpointee->isFunctionType()) {
2849 if (getLangOptions().CPlusPlus) {
2850 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2851 << lex->getType() << lex->getSourceRange();
2852 return QualType();
2853 }
2854
2855 // GNU extension: arithmetic on pointer to function
2856 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2857 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002858 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002859 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002860 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002861 return QualType();
2862 }
2863 }
2864
2865 // The result type of a pointer-int computation is the pointer type.
2866 if (rex->getType()->isIntegerType())
2867 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002868
Chris Lattnerf6da2912007-12-09 21:53:25 +00002869 // Handle pointer-pointer subtractions.
2870 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002871 QualType rpointee = RHSPTy->getPointeeType();
2872
Chris Lattnerf6da2912007-12-09 21:53:25 +00002873 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002874 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002875 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002876 if (rpointee->isVoidType()) {
2877 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002878 Diag(Loc, diag::ext_gnu_void_ptr)
2879 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002880 } else if (rpointee->isFunctionType()) {
2881 if (getLangOptions().CPlusPlus) {
2882 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2883 << rex->getType() << rex->getSourceRange();
2884 return QualType();
2885 }
2886
2887 // GNU extension: arithmetic on pointer to function
2888 if (!lpointee->isFunctionType())
2889 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2890 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002891 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002892 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002893 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002894 return QualType();
2895 }
2896 }
2897
2898 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002899 if (!Context.typesAreCompatible(
2900 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2901 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002902 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002903 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002904 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002905 return QualType();
2906 }
2907
2908 return Context.getPointerDiffType();
2909 }
2910 }
2911
Chris Lattner1eafdea2008-11-18 01:30:42 +00002912 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002913}
2914
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002915// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002916QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002917 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002918 // C99 6.5.7p2: Each of the operands shall have integer type.
2919 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002920 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002921
Chris Lattner2c8bff72007-12-12 05:47:28 +00002922 // Shifts don't perform usual arithmetic conversions, they just do integer
2923 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002924 if (!isCompAssign)
2925 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002926 UsualUnaryConversions(rex);
2927
2928 // "The type of the result is that of the promoted left operand."
2929 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002930}
2931
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002932// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002933QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002934 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002935 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002936 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002937
Chris Lattner254f3bc2007-08-26 01:18:55 +00002938 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002939 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2940 UsualArithmeticConversions(lex, rex);
2941 else {
2942 UsualUnaryConversions(lex);
2943 UsualUnaryConversions(rex);
2944 }
Chris Lattner4b009652007-07-25 00:24:17 +00002945 QualType lType = lex->getType();
2946 QualType rType = rex->getType();
2947
Ted Kremenek486509e2007-10-29 17:13:39 +00002948 // For non-floating point types, check for self-comparisons of the form
2949 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2950 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002951 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002952 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2953 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002954 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002955 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002956 }
2957
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002958 // The result of comparisons is 'bool' in C++, 'int' in C.
2959 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2960
Chris Lattner254f3bc2007-08-26 01:18:55 +00002961 if (isRelational) {
2962 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002963 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002964 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002965 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002966 if (lType->isFloatingType()) {
2967 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002968 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002969 }
2970
Chris Lattner254f3bc2007-08-26 01:18:55 +00002971 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002972 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002973 }
Chris Lattner4b009652007-07-25 00:24:17 +00002974
Chris Lattner22be8422007-08-26 01:10:14 +00002975 bool LHSIsNull = lex->isNullPointerConstant(Context);
2976 bool RHSIsNull = rex->isNullPointerConstant(Context);
2977
Chris Lattner254f3bc2007-08-26 01:18:55 +00002978 // All of the following pointer related warnings are GCC extensions, except
2979 // when handling null pointer constants. One day, we can consider making them
2980 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002981 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002982 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002983 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002984 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002985 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002986
Steve Naroff3b435622007-11-13 14:57:38 +00002987 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002988 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2989 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002990 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00002991 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002992 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002993 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002994 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002995 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002996 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002997 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002998 // Handle block pointer types.
2999 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3000 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3001 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3002
3003 if (!LHSIsNull && !RHSIsNull &&
3004 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003005 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003006 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003007 }
3008 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003009 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003010 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003011 // Allow block pointers to be compared with null pointer constants.
3012 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3013 (lType->isPointerType() && rType->isBlockPointerType())) {
3014 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003015 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003016 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003017 }
3018 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003019 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003020 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003021
Steve Naroff936c4362008-06-03 14:04:54 +00003022 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003023 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003024 const PointerType *LPT = lType->getAsPointerType();
3025 const PointerType *RPT = rType->getAsPointerType();
3026 bool LPtrToVoid = LPT ?
3027 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3028 bool RPtrToVoid = RPT ?
3029 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3030
3031 if (!LPtrToVoid && !RPtrToVoid &&
3032 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003033 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003034 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003035 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003036 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003037 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003038 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003039 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003040 }
Steve Naroff936c4362008-06-03 14:04:54 +00003041 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3042 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003043 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003044 } else {
3045 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003046 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003047 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003048 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003049 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003050 }
Steve Naroff936c4362008-06-03 14:04:54 +00003051 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003052 }
Steve Naroff936c4362008-06-03 14:04:54 +00003053 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3054 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003055 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003056 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003057 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003058 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003059 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003060 }
Steve Naroff936c4362008-06-03 14:04:54 +00003061 if (lType->isIntegerType() &&
3062 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003063 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003064 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003065 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003066 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003067 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003068 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003069 // Handle block pointers.
3070 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3071 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003072 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003073 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003074 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003075 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003076 }
3077 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3078 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003079 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003080 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003081 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003082 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003083 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003084 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003085}
3086
Nate Begemanc5f0f652008-07-14 18:02:46 +00003087/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3088/// operates on extended vector types. Instead of producing an IntTy result,
3089/// like a scalar comparison, a vector comparison produces a vector of integer
3090/// types.
3091QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003092 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003093 bool isRelational) {
3094 // Check to make sure we're operating on vectors of the same type and width,
3095 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003096 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003097 if (vType.isNull())
3098 return vType;
3099
3100 QualType lType = lex->getType();
3101 QualType rType = rex->getType();
3102
3103 // For non-floating point types, check for self-comparisons of the form
3104 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3105 // often indicate logic errors in the program.
3106 if (!lType->isFloatingType()) {
3107 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3108 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3109 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003110 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003111 }
3112
3113 // Check for comparisons of floating point operands using != and ==.
3114 if (!isRelational && lType->isFloatingType()) {
3115 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003116 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003117 }
3118
3119 // Return the type for the comparison, which is the same as vector type for
3120 // integer vectors, or an integer type of identical size and number of
3121 // elements for floating point vectors.
3122 if (lType->isIntegerType())
3123 return lType;
3124
3125 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003126 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003127 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003128 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003129 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3130 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3131
3132 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3133 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003134 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3135}
3136
Chris Lattner4b009652007-07-25 00:24:17 +00003137inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003138 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003139{
3140 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003141 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003142
Steve Naroff8f708362007-08-24 19:07:16 +00003143 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003144
3145 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003146 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003147 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003148}
3149
3150inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003151 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003152{
3153 UsualUnaryConversions(lex);
3154 UsualUnaryConversions(rex);
3155
Eli Friedmanbea3f842008-05-13 20:16:47 +00003156 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003157 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003158 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003159}
3160
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003161/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3162/// is a read-only property; return true if so. A readonly property expression
3163/// depends on various declarations and thus must be treated specially.
3164///
3165static bool IsReadonlyProperty(Expr *E, Sema &S)
3166{
3167 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3168 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3169 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3170 QualType BaseType = PropExpr->getBase()->getType();
3171 if (const PointerType *PTy = BaseType->getAsPointerType())
3172 if (const ObjCInterfaceType *IFTy =
3173 PTy->getPointeeType()->getAsObjCInterfaceType())
3174 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3175 if (S.isPropertyReadonly(PDecl, IFace))
3176 return true;
3177 }
3178 }
3179 return false;
3180}
3181
Chris Lattner4c2642c2008-11-18 01:22:49 +00003182/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3183/// emit an error and return true. If so, return false.
3184static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003185 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3186 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3187 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003188 if (IsLV == Expr::MLV_Valid)
3189 return false;
3190
3191 unsigned Diag = 0;
3192 bool NeedType = false;
3193 switch (IsLV) { // C99 6.5.16p2
3194 default: assert(0 && "Unknown result from isModifiableLvalue!");
3195 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003196 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003197 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3198 NeedType = true;
3199 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003200 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003201 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3202 NeedType = true;
3203 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003204 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003205 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3206 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003207 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003208 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3209 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003210 case Expr::MLV_IncompleteType:
3211 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003212 return S.DiagnoseIncompleteType(Loc, E->getType(),
3213 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3214 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003215 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003216 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3217 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003218 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003219 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3220 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003221 case Expr::MLV_ReadonlyProperty:
3222 Diag = diag::error_readonly_property_assignment;
3223 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003224 case Expr::MLV_NoSetterProperty:
3225 Diag = diag::error_nosetter_property_assignment;
3226 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003227 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003228
Chris Lattner4c2642c2008-11-18 01:22:49 +00003229 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003230 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003231 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003232 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003233 return true;
3234}
3235
3236
3237
3238// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003239QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3240 SourceLocation Loc,
3241 QualType CompoundType) {
3242 // Verify that LHS is a modifiable lvalue, and emit error if not.
3243 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003244 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003245
3246 QualType LHSType = LHS->getType();
3247 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003248
Chris Lattner005ed752008-01-04 18:04:52 +00003249 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003250 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003251 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003252 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003253 // Special case of NSObject attributes on c-style pointer types.
3254 if (ConvTy == IncompatiblePointer &&
3255 ((Context.isObjCNSObjectType(LHSType) &&
3256 Context.isObjCObjectPointerType(RHSType)) ||
3257 (Context.isObjCNSObjectType(RHSType) &&
3258 Context.isObjCObjectPointerType(LHSType))))
3259 ConvTy = Compatible;
3260
Chris Lattner34c85082008-08-21 18:04:13 +00003261 // If the RHS is a unary plus or minus, check to see if they = and + are
3262 // right next to each other. If so, the user may have typo'd "x =+ 4"
3263 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003264 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003265 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3266 RHSCheck = ICE->getSubExpr();
3267 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3268 if ((UO->getOpcode() == UnaryOperator::Plus ||
3269 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003270 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003271 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003272 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003273 Diag(Loc, diag::warn_not_compound_assign)
3274 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3275 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003276 }
3277 } else {
3278 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003279 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003280 }
Chris Lattner005ed752008-01-04 18:04:52 +00003281
Chris Lattner1eafdea2008-11-18 01:30:42 +00003282 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3283 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003284 return QualType();
3285
Chris Lattner4b009652007-07-25 00:24:17 +00003286 // C99 6.5.16p3: The type of an assignment expression is the type of the
3287 // left operand unless the left operand has qualified type, in which case
3288 // it is the unqualified version of the type of the left operand.
3289 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3290 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003291 // C++ 5.17p1: the type of the assignment expression is that of its left
3292 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003293 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003294}
3295
Chris Lattner1eafdea2008-11-18 01:30:42 +00003296// C99 6.5.17
3297QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3298 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003299
3300 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003301 DefaultFunctionArrayConversion(RHS);
3302 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003303}
3304
3305/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3306/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003307QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3308 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003309 QualType ResType = Op->getType();
3310 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003311
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003312 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3313 // Decrement of bool is not allowed.
3314 if (!isInc) {
3315 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3316 return QualType();
3317 }
3318 // Increment of bool sets it to true, but is deprecated.
3319 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3320 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003321 // OK!
3322 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3323 // C99 6.5.2.4p2, 6.5.6p2
3324 if (PT->getPointeeType()->isObjectType()) {
3325 // Pointer to object is ok!
3326 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003327 if (getLangOptions().CPlusPlus) {
3328 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3329 << Op->getSourceRange();
3330 return QualType();
3331 }
3332
3333 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003334 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003335 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003336 if (getLangOptions().CPlusPlus) {
3337 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3338 << Op->getType() << Op->getSourceRange();
3339 return QualType();
3340 }
3341
3342 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003343 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003344 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003345 } else {
3346 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3347 diag::err_typecheck_arithmetic_incomplete_type,
3348 Op->getSourceRange(), SourceRange(),
3349 ResType);
3350 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003351 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003352 } else if (ResType->isComplexType()) {
3353 // C99 does not support ++/-- on complex types, we allow as an extension.
3354 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003355 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003356 } else {
3357 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003358 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003359 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003360 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003361 // At this point, we know we have a real, complex or pointer type.
3362 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003363 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003364 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003365 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003366}
3367
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003368/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003369/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003370/// where the declaration is needed for type checking. We only need to
3371/// handle cases when the expression references a function designator
3372/// or is an lvalue. Here are some examples:
3373/// - &(x) => x
3374/// - &*****f => f for f a function designator.
3375/// - &s.xx => s
3376/// - &s.zz[1].yy -> s, if zz is an array
3377/// - *(x + 1) -> x, if x is an array
3378/// - &"123"[2] -> 0
3379/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003380static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003381 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003382 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003383 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003384 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003385 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003386 // Fields cannot be declared with a 'register' storage class.
3387 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003388 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003389 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003390 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003391 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003392 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003393
Douglas Gregord2baafd2008-10-21 16:13:35 +00003394 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003395 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003396 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003397 return 0;
3398 else
3399 return VD;
3400 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003401 case Stmt::UnaryOperatorClass: {
3402 UnaryOperator *UO = cast<UnaryOperator>(E);
3403
3404 switch(UO->getOpcode()) {
3405 case UnaryOperator::Deref: {
3406 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003407 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3408 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3409 if (!VD || VD->getType()->isPointerType())
3410 return 0;
3411 return VD;
3412 }
3413 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003414 }
3415 case UnaryOperator::Real:
3416 case UnaryOperator::Imag:
3417 case UnaryOperator::Extension:
3418 return getPrimaryDecl(UO->getSubExpr());
3419 default:
3420 return 0;
3421 }
3422 }
3423 case Stmt::BinaryOperatorClass: {
3424 BinaryOperator *BO = cast<BinaryOperator>(E);
3425
3426 // Handle cases involving pointer arithmetic. The result of an
3427 // Assign or AddAssign is not an lvalue so they can be ignored.
3428
3429 // (x + n) or (n + x) => x
3430 if (BO->getOpcode() == BinaryOperator::Add) {
3431 if (BO->getLHS()->getType()->isPointerType()) {
3432 return getPrimaryDecl(BO->getLHS());
3433 } else if (BO->getRHS()->getType()->isPointerType()) {
3434 return getPrimaryDecl(BO->getRHS());
3435 }
3436 }
3437
3438 return 0;
3439 }
Chris Lattner4b009652007-07-25 00:24:17 +00003440 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003441 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003442 case Stmt::ImplicitCastExprClass:
3443 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003444 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003445 default:
3446 return 0;
3447 }
3448}
3449
3450/// CheckAddressOfOperand - The operand of & must be either a function
3451/// designator or an lvalue designating an object. If it is an lvalue, the
3452/// object cannot be declared with storage class register or be a bit field.
3453/// Note: The usual conversions are *not* applied to the operand of the &
3454/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003455/// In C++, the operand might be an overloaded function name, in which case
3456/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003457QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003458 if (op->isTypeDependent())
3459 return Context.DependentTy;
3460
Steve Naroff9c6c3592008-01-13 17:10:08 +00003461 if (getLangOptions().C99) {
3462 // Implement C99-only parts of addressof rules.
3463 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3464 if (uOp->getOpcode() == UnaryOperator::Deref)
3465 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3466 // (assuming the deref expression is valid).
3467 return uOp->getSubExpr()->getType();
3468 }
3469 // Technically, there should be a check for array subscript
3470 // expressions here, but the result of one is always an lvalue anyway.
3471 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003472 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003473 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003474
Chris Lattner4b009652007-07-25 00:24:17 +00003475 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003476 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3477 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003478 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3479 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003480 return QualType();
3481 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003482 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003483 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3484 if (Field->isBitField()) {
3485 Diag(OpLoc, diag::err_typecheck_address_of)
3486 << "bit-field" << op->getSourceRange();
3487 return QualType();
3488 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003489 }
3490 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003491 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3492 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003493 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003494 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003495 return QualType();
3496 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003497 // We have an lvalue with a decl. Make sure the decl is not declared
3498 // with the register storage-class specifier.
3499 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3500 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003501 Diag(OpLoc, diag::err_typecheck_address_of)
3502 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003503 return QualType();
3504 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003505 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003506 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003507 } else if (isa<FieldDecl>(dcl)) {
3508 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003509 // Could be a pointer to member, though, if there is an explicit
3510 // scope qualifier for the class.
3511 if (isa<QualifiedDeclRefExpr>(op)) {
3512 DeclContext *Ctx = dcl->getDeclContext();
3513 if (Ctx && Ctx->isRecord())
3514 return Context.getMemberPointerType(op->getType(),
3515 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3516 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003517 } else if (isa<FunctionDecl>(dcl)) {
3518 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003519 // As above.
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 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003526 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003527 else
Chris Lattner4b009652007-07-25 00:24:17 +00003528 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003529 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003530
Chris Lattner4b009652007-07-25 00:24:17 +00003531 // If the operand has type "type", the result has type "pointer to type".
3532 return Context.getPointerType(op->getType());
3533}
3534
Chris Lattnerda5c0872008-11-23 09:13:29 +00003535QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3536 UsualUnaryConversions(Op);
3537 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003538
Chris Lattnerda5c0872008-11-23 09:13:29 +00003539 // Note that per both C89 and C99, this is always legal, even if ptype is an
3540 // incomplete type or void. It would be possible to warn about dereferencing
3541 // a void pointer, but it's completely well-defined, and such a warning is
3542 // unlikely to catch any mistakes.
3543 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003544 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003545
Chris Lattner77d52da2008-11-20 06:06:08 +00003546 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003547 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003548 return QualType();
3549}
3550
3551static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3552 tok::TokenKind Kind) {
3553 BinaryOperator::Opcode Opc;
3554 switch (Kind) {
3555 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003556 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3557 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003558 case tok::star: Opc = BinaryOperator::Mul; break;
3559 case tok::slash: Opc = BinaryOperator::Div; break;
3560 case tok::percent: Opc = BinaryOperator::Rem; break;
3561 case tok::plus: Opc = BinaryOperator::Add; break;
3562 case tok::minus: Opc = BinaryOperator::Sub; break;
3563 case tok::lessless: Opc = BinaryOperator::Shl; break;
3564 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3565 case tok::lessequal: Opc = BinaryOperator::LE; break;
3566 case tok::less: Opc = BinaryOperator::LT; break;
3567 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3568 case tok::greater: Opc = BinaryOperator::GT; break;
3569 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3570 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3571 case tok::amp: Opc = BinaryOperator::And; break;
3572 case tok::caret: Opc = BinaryOperator::Xor; break;
3573 case tok::pipe: Opc = BinaryOperator::Or; break;
3574 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3575 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3576 case tok::equal: Opc = BinaryOperator::Assign; break;
3577 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3578 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3579 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3580 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3581 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3582 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3583 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3584 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3585 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3586 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3587 case tok::comma: Opc = BinaryOperator::Comma; break;
3588 }
3589 return Opc;
3590}
3591
3592static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3593 tok::TokenKind Kind) {
3594 UnaryOperator::Opcode Opc;
3595 switch (Kind) {
3596 default: assert(0 && "Unknown unary op!");
3597 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3598 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3599 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3600 case tok::star: Opc = UnaryOperator::Deref; break;
3601 case tok::plus: Opc = UnaryOperator::Plus; break;
3602 case tok::minus: Opc = UnaryOperator::Minus; break;
3603 case tok::tilde: Opc = UnaryOperator::Not; break;
3604 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003605 case tok::kw___real: Opc = UnaryOperator::Real; break;
3606 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3607 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3608 }
3609 return Opc;
3610}
3611
Douglas Gregord7f915e2008-11-06 23:29:22 +00003612/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3613/// operator @p Opc at location @c TokLoc. This routine only supports
3614/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003615Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3616 unsigned Op,
3617 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003618 QualType ResultTy; // Result type of the binary operator.
3619 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3620 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3621
3622 switch (Opc) {
3623 default:
3624 assert(0 && "Unknown binary expr!");
3625 case BinaryOperator::Assign:
3626 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3627 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003628 case BinaryOperator::PtrMemD:
3629 case BinaryOperator::PtrMemI:
3630 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3631 Opc == BinaryOperator::PtrMemI);
3632 break;
3633 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003634 case BinaryOperator::Div:
3635 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3636 break;
3637 case BinaryOperator::Rem:
3638 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3639 break;
3640 case BinaryOperator::Add:
3641 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3642 break;
3643 case BinaryOperator::Sub:
3644 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3645 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003646 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003647 case BinaryOperator::Shr:
3648 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3649 break;
3650 case BinaryOperator::LE:
3651 case BinaryOperator::LT:
3652 case BinaryOperator::GE:
3653 case BinaryOperator::GT:
3654 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3655 break;
3656 case BinaryOperator::EQ:
3657 case BinaryOperator::NE:
3658 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3659 break;
3660 case BinaryOperator::And:
3661 case BinaryOperator::Xor:
3662 case BinaryOperator::Or:
3663 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3664 break;
3665 case BinaryOperator::LAnd:
3666 case BinaryOperator::LOr:
3667 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3668 break;
3669 case BinaryOperator::MulAssign:
3670 case BinaryOperator::DivAssign:
3671 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3672 if (!CompTy.isNull())
3673 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3674 break;
3675 case BinaryOperator::RemAssign:
3676 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3677 if (!CompTy.isNull())
3678 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3679 break;
3680 case BinaryOperator::AddAssign:
3681 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3682 if (!CompTy.isNull())
3683 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3684 break;
3685 case BinaryOperator::SubAssign:
3686 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3687 if (!CompTy.isNull())
3688 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3689 break;
3690 case BinaryOperator::ShlAssign:
3691 case BinaryOperator::ShrAssign:
3692 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3693 if (!CompTy.isNull())
3694 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3695 break;
3696 case BinaryOperator::AndAssign:
3697 case BinaryOperator::XorAssign:
3698 case BinaryOperator::OrAssign:
3699 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3700 if (!CompTy.isNull())
3701 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3702 break;
3703 case BinaryOperator::Comma:
3704 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3705 break;
3706 }
3707 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003708 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003709 if (CompTy.isNull())
3710 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3711 else
3712 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003713 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003714}
3715
Chris Lattner4b009652007-07-25 00:24:17 +00003716// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003717Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3718 tok::TokenKind Kind,
3719 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003720 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003721 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003722
Steve Naroff87d58b42007-09-16 03:34:24 +00003723 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3724 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003725
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003726 // If either expression is type-dependent, just build the AST.
3727 // FIXME: We'll need to perform some caching of the result of name
3728 // lookup for operator+.
3729 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003730 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3731 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003732 Context.DependentTy,
3733 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003734 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003735 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3736 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003737 }
3738
Sebastian Redl95216a62009-02-07 00:15:38 +00003739 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003740 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3741 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003742 // If this is one of the assignment operators, we only perform
3743 // overload resolution if the left-hand side is a class or
3744 // enumeration type (C++ [expr.ass]p3).
3745 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3746 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3747 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3748 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003749
Douglas Gregord7f915e2008-11-06 23:29:22 +00003750 // Determine which overloaded operator we're dealing with.
3751 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003752 // Overloading .* is not possible.
3753 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003754 OO_Star, OO_Slash, OO_Percent,
3755 OO_Plus, OO_Minus,
3756 OO_LessLess, OO_GreaterGreater,
3757 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3758 OO_EqualEqual, OO_ExclaimEqual,
3759 OO_Amp,
3760 OO_Caret,
3761 OO_Pipe,
3762 OO_AmpAmp,
3763 OO_PipePipe,
3764 OO_Equal, OO_StarEqual,
3765 OO_SlashEqual, OO_PercentEqual,
3766 OO_PlusEqual, OO_MinusEqual,
3767 OO_LessLessEqual, OO_GreaterGreaterEqual,
3768 OO_AmpEqual, OO_CaretEqual,
3769 OO_PipeEqual,
3770 OO_Comma
3771 };
3772 OverloadedOperatorKind OverOp = OverOps[Opc];
3773
Douglas Gregor5ed15042008-11-18 23:14:02 +00003774 // Add the appropriate overloaded operators (C++ [over.match.oper])
3775 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003776 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003777 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003778 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3779 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003780
3781 // Perform overload resolution.
3782 OverloadCandidateSet::iterator Best;
3783 switch (BestViableFunction(CandidateSet, Best)) {
3784 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003785 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003786 FunctionDecl *FnDecl = Best->Function;
3787
Douglas Gregor70d26122008-11-12 17:17:38 +00003788 if (FnDecl) {
3789 // We matched an overloaded operator. Build a call to that
3790 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003791
Douglas Gregor70d26122008-11-12 17:17:38 +00003792 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3794 if (PerformObjectArgumentInitialization(lhs, Method) ||
3795 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3796 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003797 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003798 } else {
3799 // Convert the arguments.
3800 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3801 "passing") ||
3802 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3803 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003804 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003805 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003806
Douglas Gregor70d26122008-11-12 17:17:38 +00003807 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003808 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003809 = FnDecl->getType()->getAsFunctionType()->getResultType();
3810 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003811
Douglas Gregor70d26122008-11-12 17:17:38 +00003812 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003813 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3814 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003815 UsualUnaryConversions(FnExpr);
3816
Ted Kremenek362abcd2009-02-09 20:51:47 +00003817 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003818 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003819 } else {
3820 // We matched a built-in operator. Convert the arguments, then
3821 // break out so that we will build the appropriate built-in
3822 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003823 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3824 Best->Conversions[0], "passing") ||
3825 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3826 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003827 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003828
3829 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003830 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003831 }
3832
3833 case OR_No_Viable_Function:
3834 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003835 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003836 break;
3837
3838 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003839 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3840 << BinaryOperator::getOpcodeStr(Opc)
3841 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003842 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003843 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003844 }
3845
Douglas Gregor70d26122008-11-12 17:17:38 +00003846 // Either we found no viable overloaded operator or we matched a
3847 // built-in operator. In either case, fall through to trying to
3848 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003849 }
3850
Douglas Gregord7f915e2008-11-06 23:29:22 +00003851 // Build a built-in binary operation.
3852 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003853}
3854
3855// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003856Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3857 tok::TokenKind Op, ExprArg input) {
3858 // FIXME: Input is modified later, but smart pointer not reassigned.
3859 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003860 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003861
3862 if (getLangOptions().CPlusPlus &&
3863 (Input->getType()->isRecordType()
3864 || Input->getType()->isEnumeralType())) {
3865 // Determine which overloaded operator we're dealing with.
3866 static const OverloadedOperatorKind OverOps[] = {
3867 OO_None, OO_None,
3868 OO_PlusPlus, OO_MinusMinus,
3869 OO_Amp, OO_Star,
3870 OO_Plus, OO_Minus,
3871 OO_Tilde, OO_Exclaim,
3872 OO_None, OO_None,
3873 OO_None,
3874 OO_None
3875 };
3876 OverloadedOperatorKind OverOp = OverOps[Opc];
3877
3878 // Add the appropriate overloaded operators (C++ [over.match.oper])
3879 // to the candidate set.
3880 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003881 if (OverOp != OO_None &&
3882 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3883 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003884
3885 // Perform overload resolution.
3886 OverloadCandidateSet::iterator Best;
3887 switch (BestViableFunction(CandidateSet, Best)) {
3888 case OR_Success: {
3889 // We found a built-in operator or an overloaded operator.
3890 FunctionDecl *FnDecl = Best->Function;
3891
3892 if (FnDecl) {
3893 // We matched an overloaded operator. Build a call to that
3894 // operator.
3895
3896 // Convert the arguments.
3897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3898 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003899 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003900 } else {
3901 // Convert the arguments.
3902 if (PerformCopyInitialization(Input,
3903 FnDecl->getParamDecl(0)->getType(),
3904 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003905 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003906 }
3907
3908 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003909 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003910 = FnDecl->getType()->getAsFunctionType()->getResultType();
3911 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003912
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003913 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003914 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3915 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003916 UsualUnaryConversions(FnExpr);
3917
Sebastian Redl8b769972009-01-19 00:08:26 +00003918 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003919 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003920 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003921 } else {
3922 // We matched a built-in operator. Convert the arguments, then
3923 // break out so that we will build the appropriate built-in
3924 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003925 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3926 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003927 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003928
3929 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003930 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003931 }
3932
3933 case OR_No_Viable_Function:
3934 // No viable function; fall through to handling this as a
3935 // built-in operator, which will produce an error message for us.
3936 break;
3937
3938 case OR_Ambiguous:
3939 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3940 << UnaryOperator::getOpcodeStr(Opc)
3941 << Input->getSourceRange();
3942 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003943 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003944 }
3945
3946 // Either we found no viable overloaded operator or we matched a
3947 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003948 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003949 }
3950
Chris Lattner4b009652007-07-25 00:24:17 +00003951 QualType resultType;
3952 switch (Opc) {
3953 default:
3954 assert(0 && "Unimplemented unary expr!");
3955 case UnaryOperator::PreInc:
3956 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003957 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3958 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003959 break;
3960 case UnaryOperator::AddrOf:
3961 resultType = CheckAddressOfOperand(Input, OpLoc);
3962 break;
3963 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003964 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003965 resultType = CheckIndirectionOperand(Input, OpLoc);
3966 break;
3967 case UnaryOperator::Plus:
3968 case UnaryOperator::Minus:
3969 UsualUnaryConversions(Input);
3970 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003971 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3972 break;
3973 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3974 resultType->isEnumeralType())
3975 break;
3976 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3977 Opc == UnaryOperator::Plus &&
3978 resultType->isPointerType())
3979 break;
3980
Sebastian Redl8b769972009-01-19 00:08:26 +00003981 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3982 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003983 case UnaryOperator::Not: // bitwise complement
3984 UsualUnaryConversions(Input);
3985 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003986 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3987 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3988 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003989 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003990 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003991 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003992 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3993 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003994 break;
3995 case UnaryOperator::LNot: // logical negation
3996 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3997 DefaultFunctionArrayConversion(Input);
3998 resultType = Input->getType();
3999 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004000 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4001 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004002 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004003 // In C++, it's bool. C++ 5.3.1p8
4004 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004005 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004006 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004007 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00004008 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00004009 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004010 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004011 resultType = Input->getType();
4012 break;
4013 }
4014 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004015 return ExprError();
4016 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004017 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004018}
4019
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004020/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4021Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004022 SourceLocation LabLoc,
4023 IdentifierInfo *LabelII) {
4024 // Look up the record for this label identifier.
4025 LabelStmt *&LabelDecl = LabelMap[LabelII];
4026
Daniel Dunbar879788d2008-08-04 16:51:22 +00004027 // If we haven't seen this label yet, create a forward reference. It
4028 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004029 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004030 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004031
4032 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004033 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4034 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004035}
4036
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004037Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004038 SourceLocation RPLoc) { // "({..})"
4039 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4040 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4041 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4042
Eli Friedmanbc941e12009-01-24 23:09:00 +00004043 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4044 if (isFileScope) {
4045 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4046 }
4047
Chris Lattner4b009652007-07-25 00:24:17 +00004048 // FIXME: there are a variety of strange constraints to enforce here, for
4049 // example, it is not possible to goto into a stmt expression apparently.
4050 // More semantic analysis is needed.
4051
4052 // FIXME: the last statement in the compount stmt has its value used. We
4053 // should not warn about it being unused.
4054
4055 // If there are sub stmts in the compound stmt, take the type of the last one
4056 // as the type of the stmtexpr.
4057 QualType Ty = Context.VoidTy;
4058
Chris Lattner200964f2008-07-26 19:51:01 +00004059 if (!Compound->body_empty()) {
4060 Stmt *LastStmt = Compound->body_back();
4061 // If LastStmt is a label, skip down through into the body.
4062 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4063 LastStmt = Label->getSubStmt();
4064
4065 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004066 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004067 }
Chris Lattner4b009652007-07-25 00:24:17 +00004068
Steve Naroff774e4152009-01-21 00:14:39 +00004069 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004070}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004071
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004072Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4073 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004074 SourceLocation TypeLoc,
4075 TypeTy *argty,
4076 OffsetOfComponent *CompPtr,
4077 unsigned NumComponents,
4078 SourceLocation RPLoc) {
4079 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4080 assert(!ArgTy.isNull() && "Missing type argument!");
4081
4082 // We must have at least one component that refers to the type, and the first
4083 // one is known to be a field designator. Verify that the ArgTy represents
4084 // a struct/union/class.
4085 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004086 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004087
4088 // Otherwise, create a compound literal expression as the base, and
4089 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004090 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004091 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004092 IList->setType(ArgTy);
4093 Expr *Res =
4094 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4095
Chris Lattnerb37522e2007-08-31 21:49:13 +00004096 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4097 // GCC extension, diagnose them.
4098 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004099 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4100 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004101
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004102 for (unsigned i = 0; i != NumComponents; ++i) {
4103 const OffsetOfComponent &OC = CompPtr[i];
4104 if (OC.isBrackets) {
4105 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004106 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004107 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004108 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004109 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004110 }
4111
Chris Lattner2af6a802007-08-30 17:59:59 +00004112 // FIXME: C++: Verify that operator[] isn't overloaded.
4113
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004114 // C99 6.5.2.1p1
4115 Expr *Idx = static_cast<Expr*>(OC.U.E);
4116 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004117 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4118 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004119
Steve Naroff774e4152009-01-21 00:14:39 +00004120 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4121 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004122 continue;
4123 }
4124
4125 const RecordType *RC = Res->getType()->getAsRecordType();
4126 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004127 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004128 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004129 }
4130
4131 // Get the decl corresponding to this.
4132 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004133 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004134 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4135 LookupMemberName)
4136 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004137 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004138 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4139 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004140
4141 // FIXME: C++: Verify that MemberDecl isn't a static field.
4142 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004143 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4144 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004145 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4146 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004147 }
4148
Steve Naroff774e4152009-01-21 00:14:39 +00004149 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4150 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004151}
4152
4153
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004154Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004155 TypeTy *arg1, TypeTy *arg2,
4156 SourceLocation RPLoc) {
4157 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4158 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4159
4160 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4161
Steve Naroff774e4152009-01-21 00:14:39 +00004162 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4163 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004164}
4165
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004166Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004167 ExprTy *expr1, ExprTy *expr2,
4168 SourceLocation RPLoc) {
4169 Expr *CondExpr = static_cast<Expr*>(cond);
4170 Expr *LHSExpr = static_cast<Expr*>(expr1);
4171 Expr *RHSExpr = static_cast<Expr*>(expr2);
4172
4173 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4174
4175 // The conditional expression is required to be a constant expression.
4176 llvm::APSInt condEval(32);
4177 SourceLocation ExpLoc;
4178 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004179 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4180 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004181
4182 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4183 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4184 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004185 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4186 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004187}
4188
Steve Naroff52a81c02008-09-03 18:15:37 +00004189//===----------------------------------------------------------------------===//
4190// Clang Extensions.
4191//===----------------------------------------------------------------------===//
4192
4193/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004194void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004195 // Analyze block parameters.
4196 BlockSemaInfo *BSI = new BlockSemaInfo();
4197
4198 // Add BSI to CurBlock.
4199 BSI->PrevBlockInfo = CurBlock;
4200 CurBlock = BSI;
4201
4202 BSI->ReturnType = 0;
4203 BSI->TheScope = BlockScope;
4204
Steve Naroff52059382008-10-10 01:28:17 +00004205 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004206 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004207}
4208
Mike Stumpc1fddff2009-02-04 22:31:32 +00004209void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4210 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4211
4212 if (ParamInfo.getNumTypeObjects() == 0
4213 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4214 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4215
4216 // The type is entirely optional as well, if none, use DependentTy.
4217 if (T.isNull())
4218 T = Context.DependentTy;
4219
4220 // The parameter list is optional, if there was none, assume ().
4221 if (!T->isFunctionType())
4222 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4223
4224 CurBlock->hasPrototype = true;
4225 CurBlock->isVariadic = false;
4226 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4227 .getTypePtr();
4228
4229 if (!RetTy->isDependentType())
4230 CurBlock->ReturnType = RetTy;
4231 return;
4232 }
4233
Steve Naroff52a81c02008-09-03 18:15:37 +00004234 // Analyze arguments to block.
4235 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4236 "Not a function declarator!");
4237 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004238
Steve Naroff52059382008-10-10 01:28:17 +00004239 CurBlock->hasPrototype = FTI.hasPrototype;
4240 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004241
4242 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4243 // no arguments, not a function that takes a single void argument.
4244 if (FTI.hasPrototype &&
4245 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4246 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4247 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4248 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004249 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004250 } else if (FTI.hasPrototype) {
4251 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004252 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4253 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004254 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4255
4256 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4257 .getTypePtr();
4258
4259 if (!RetTy->isDependentType())
4260 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004261 }
Steve Naroff52059382008-10-10 01:28:17 +00004262 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4263
4264 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4265 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4266 // If this has an identifier, add it to the scope stack.
4267 if ((*AI)->getIdentifier())
4268 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004269}
4270
4271/// ActOnBlockError - If there is an error parsing a block, this callback
4272/// is invoked to pop the information about the block from the action impl.
4273void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4274 // Ensure that CurBlock is deleted.
4275 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4276
4277 // Pop off CurBlock, handle nested blocks.
4278 CurBlock = CurBlock->PrevBlockInfo;
4279
4280 // FIXME: Delete the ParmVarDecl objects as well???
4281
4282}
4283
4284/// ActOnBlockStmtExpr - This is called when the body of a block statement
4285/// literal was successfully completed. ^(int x){...}
4286Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4287 Scope *CurScope) {
4288 // Ensure that CurBlock is deleted.
4289 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004290 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004291
Steve Naroff52059382008-10-10 01:28:17 +00004292 PopDeclContext();
4293
Steve Naroff52a81c02008-09-03 18:15:37 +00004294 // Pop off CurBlock, handle nested blocks.
4295 CurBlock = CurBlock->PrevBlockInfo;
4296
4297 QualType RetTy = Context.VoidTy;
4298 if (BSI->ReturnType)
4299 RetTy = QualType(BSI->ReturnType, 0);
4300
4301 llvm::SmallVector<QualType, 8> ArgTypes;
4302 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4303 ArgTypes.push_back(BSI->Params[i]->getType());
4304
4305 QualType BlockTy;
4306 if (!BSI->hasPrototype)
4307 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4308 else
4309 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004310 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004311
4312 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004313
Steve Naroff95029d92008-10-08 18:44:00 +00004314 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004315 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004316}
4317
Nate Begemanbd881ef2008-01-30 20:50:20 +00004318/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004319/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004320/// The number of arguments has already been validated to match the number of
4321/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004322static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4323 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004324 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004325 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004326 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4327 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004328
4329 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004330 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004331 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004332 return true;
4333}
4334
4335Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4336 SourceLocation *CommaLocs,
4337 SourceLocation BuiltinLoc,
4338 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004339 // __builtin_overload requires at least 2 arguments
4340 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004341 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4342 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004343
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004344 // The first argument is required to be a constant expression. It tells us
4345 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004346 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004347 Expr *NParamsExpr = Args[0];
4348 llvm::APSInt constEval(32);
4349 SourceLocation ExpLoc;
4350 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004351 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4352 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004353
4354 // Verify that the number of parameters is > 0
4355 unsigned NumParams = constEval.getZExtValue();
4356 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004357 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4358 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004359 // Verify that we have at least 1 + NumParams arguments to the builtin.
4360 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004361 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4362 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004363
4364 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004365 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004366 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004367 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4368 // UsualUnaryConversions will convert the function DeclRefExpr into a
4369 // pointer to function.
4370 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004371 const FunctionTypeProto *FnType = 0;
4372 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4373 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004374
4375 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4376 // parameters, and the number of parameters must match the value passed to
4377 // the builtin.
4378 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004379 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4380 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004381
4382 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004383 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004384 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004385 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004386 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004387 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4388 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004389 // Remember our match, and continue processing the remaining arguments
4390 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004391 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004392 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004393 BuiltinLoc, RParenLoc);
4394 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004395 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004396 // Return the newly created OverloadExpr node, if we succeded in matching
4397 // exactly one of the candidate functions.
4398 if (OE)
4399 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004400
4401 // If we didn't find a matching function Expr in the __builtin_overload list
4402 // the return an error.
4403 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004404 for (unsigned i = 0; i != NumParams; ++i) {
4405 if (i != 0) typeNames += ", ";
4406 typeNames += Args[i+1]->getType().getAsString();
4407 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004408
Chris Lattner77d52da2008-11-20 06:06:08 +00004409 return Diag(BuiltinLoc, diag::err_overload_no_match)
4410 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004411}
4412
Anders Carlsson36760332007-10-15 20:28:48 +00004413Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4414 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004415 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004416 Expr *E = static_cast<Expr*>(expr);
4417 QualType T = QualType::getFromOpaquePtr(type);
4418
4419 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004420
4421 // Get the va_list type
4422 QualType VaListType = Context.getBuiltinVaListType();
4423 // Deal with implicit array decay; for example, on x86-64,
4424 // va_list is an array, but it's supposed to decay to
4425 // a pointer for va_arg.
4426 if (VaListType->isArrayType())
4427 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004428 // Make sure the input expression also decays appropriately.
4429 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004430
4431 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004432 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004433 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004434 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004435
4436 // FIXME: Warn if a non-POD type is passed in.
4437
Steve Naroff774e4152009-01-21 00:14:39 +00004438 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004439}
4440
Douglas Gregorad4b3792008-11-29 04:51:27 +00004441Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4442 // The type of __null will be int or long, depending on the size of
4443 // pointers on the target.
4444 QualType Ty;
4445 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4446 Ty = Context.IntTy;
4447 else
4448 Ty = Context.LongTy;
4449
Steve Naroff774e4152009-01-21 00:14:39 +00004450 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004451}
4452
Chris Lattner005ed752008-01-04 18:04:52 +00004453bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4454 SourceLocation Loc,
4455 QualType DstType, QualType SrcType,
4456 Expr *SrcExpr, const char *Flavor) {
4457 // Decode the result (notice that AST's are still created for extensions).
4458 bool isInvalid = false;
4459 unsigned DiagKind;
4460 switch (ConvTy) {
4461 default: assert(0 && "Unknown conversion type");
4462 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004463 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004464 DiagKind = diag::ext_typecheck_convert_pointer_int;
4465 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004466 case IntToPointer:
4467 DiagKind = diag::ext_typecheck_convert_int_pointer;
4468 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004469 case IncompatiblePointer:
4470 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4471 break;
4472 case FunctionVoidPointer:
4473 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4474 break;
4475 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004476 // If the qualifiers lost were because we were applying the
4477 // (deprecated) C++ conversion from a string literal to a char*
4478 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4479 // Ideally, this check would be performed in
4480 // CheckPointerTypesForAssignment. However, that would require a
4481 // bit of refactoring (so that the second argument is an
4482 // expression, rather than a type), which should be done as part
4483 // of a larger effort to fix CheckPointerTypesForAssignment for
4484 // C++ semantics.
4485 if (getLangOptions().CPlusPlus &&
4486 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4487 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004488 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4489 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004490 case IntToBlockPointer:
4491 DiagKind = diag::err_int_to_block_pointer;
4492 break;
4493 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004494 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004495 break;
Steve Naroff19608432008-10-14 22:18:38 +00004496 case IncompatibleObjCQualifiedId:
4497 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4498 // it can give a more specific diagnostic.
4499 DiagKind = diag::warn_incompatible_qualified_id;
4500 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004501 case IncompatibleVectors:
4502 DiagKind = diag::warn_incompatible_vectors;
4503 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004504 case Incompatible:
4505 DiagKind = diag::err_typecheck_convert_incompatible;
4506 isInvalid = true;
4507 break;
4508 }
4509
Chris Lattner271d4c22008-11-24 05:29:24 +00004510 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4511 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004512 return isInvalid;
4513}
Anders Carlssond5201b92008-11-30 19:50:32 +00004514
4515bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4516{
4517 Expr::EvalResult EvalResult;
4518
4519 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4520 EvalResult.HasSideEffects) {
4521 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4522
4523 if (EvalResult.Diag) {
4524 // We only show the note if it's not the usual "invalid subexpression"
4525 // or if it's actually in a subexpression.
4526 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4527 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4528 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4529 }
4530
4531 return true;
4532 }
4533
4534 if (EvalResult.Diag) {
4535 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4536 E->getSourceRange();
4537
4538 // Print the reason it's not a constant.
4539 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4540 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4541 }
4542
4543 if (Result)
4544 *Result = EvalResult.Val.getInt();
4545 return false;
4546}