blob: 07079dbb7da4577a8c593ff07b9a5e7050a246b5 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattner76a642f2009-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 Lattnere7a2e912008-07-25 21:10:04 +000048//===----------------------------------------------------------------------===//
49// Standard Promotions and Conversions
50//===----------------------------------------------------------------------===//
51
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +000057 if (Ty->isFunctionType())
58 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-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).
Argyrios Kyrtzidisc39a3d72008-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 Lattner67d33d82008-07-25 21:33:13 +000073 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
74 }
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattner05faf172008-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 Carlssondce5e2c2009-01-16 16:48:51 +0000109// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
110// will warn if the resulting type is not a POD type.
Chris Lattner76a642f2009-02-15 22:43:40 +0000111void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-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 Lattnere7a2e912008-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 Gregoreb8f3062008-11-12 17:17:38 +0000134
Chris Lattnere7a2e912008-07-25 21:10:04 +0000135 // For conversion purposes, we ignore any qualifiers.
136 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000137 QualType lhs =
138 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
139 QualType rhs =
140 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-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 Lattner76a642f2009-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 Gregoreb8f3062008-11-12 17:17:38 +0000173
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000210 } else if (result < 0) { // The right side is bigger, convert lhs.
211 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000218 return rhs;
219 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-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 Carlsson5b1f3f02008-12-10 23:30:05 +0000228 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000229 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000230 return lhs;
231 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-07-25 21:10:04 +0000237 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000238 return rhs;
239 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-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 Lattner76a642f2009-02-15 22:43:40 +0000247 if (result > 0) // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000248 return lhs;
Chris Lattner76a642f2009-02-15 22:43:40 +0000249 assert(result < 0 && "illegal float comparison");
250 return rhs; // convert the lhs
Chris Lattnere7a2e912008-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 Lattner76a642f2009-02-15 22:43:40 +0000259 rhsComplexInt->getElementType()) >= 0)
260 return lhs; // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000261 return rhs;
262 } else if (lhsComplexInt && rhs->isIntegerType()) {
263 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000264 return lhs;
265 } else if (rhsComplexInt && lhs->isIntegerType()) {
266 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000295 return destType;
296}
297
298//===----------------------------------------------------------------------===//
299// Semantic Analysis for various Expression Types
300//===----------------------------------------------------------------------===//
301
302
Steve Narofff69936d2007-09-16 03:34:24 +0000303/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Redlcd965b92009-01-18 18:53:16 +0000308///
309Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000310Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 assert(NumStringToks && "Must have at least one string!");
312
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000313 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000315 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000316
317 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
318 for (unsigned i = 0; i != NumStringToks; ++i)
319 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000320
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000321 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000322 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000323 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Redlcd965b92009-01-18 18:53:16 +0000328
Chris Lattnera7ad98f2008-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 Redlcd965b92009-01-18 18:53:16 +0000335
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek6e94ef52009-02-06 19:55:15 +0000337 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff6ece14c2009-01-21 00:14:39 +0000338 Literal.GetStringLength(),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000339 Literal.AnyWide, StrTy,
340 StringToks[0].getLocation(),
341 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000342}
343
Chris Lattner639e2d32008-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 Naroff08d92e42007-09-15 18:49:24 +0000374/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000375/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000376/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000377/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000378/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000379Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
380 IdentifierInfo &II,
381 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000382 const CXXScopeSpec *SS,
383 bool isAddressOfOperand) {
384 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor17330012009-02-04 15:01:18 +0000385 isAddressOfOperand);
Douglas Gregor10c42622008-11-18 15:03:34 +0000386}
387
Douglas Gregor1a49af92009-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 Redlebc07d52009-02-03 20:19:35 +0000391DeclRefExpr *
392Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
393 bool TypeDependent, bool ValueDependent,
394 const CXXScopeSpec *SS) {
Steve Naroff6ece14c2009-01-21 00:14:39 +0000395 if (SS && !SS->isEmpty())
396 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroff0a473932009-01-20 19:53:53 +0000397 ValueDependent, SS->getRange().getBegin());
Steve Naroff6ece14c2009-01-21 00:14:39 +0000398 else
399 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000400}
401
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000405static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000406 assert(Record->isAnonymousStructOrUnion() &&
407 "Record must be an anonymous struct or union!");
408
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000409 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000422 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-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 Redlcd965b92009-01-18 18:53:16 +0000431Sema::OwningExprResult
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000451 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-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 Kremenek8189cde2009-02-07 01:47:29 +0000471 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000472 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregorbcbffc42009-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 Naroff6ece14c2009-01-21 00:14:39 +0000500 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000501 MD->getThisType(Context));
502 BaseObjectIsPointer = true;
503 }
504 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000505 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
506 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000507 }
508 ExtraQuals = MD->getTypeQualifiers();
509 }
510
511 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000512 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
513 << Field->getDeclName());
Douglas Gregorbcbffc42009-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 Naroff6ece14c2009-01-21 00:14:39 +0000528 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
529 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000530 BaseObjectIsPointer = false;
531 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
532 OpLoc = SourceLocation();
533 }
534
Sebastian Redlcd965b92009-01-18 18:53:16 +0000535 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000536}
537
Douglas Gregor10c42622008-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 Gregor5c37de72008-12-06 00:22:45 +0000552///
Sebastian Redlebc07d52009-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 Redlcd965b92009-01-18 18:53:16 +0000557Sema::OwningExprResult
558Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
559 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +0000560 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000561 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000562 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000563 if (SS && SS->isInvalid())
564 return ExprError();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000565 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
566 false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000567
Douglas Gregor17330012009-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 Gregor47b9a1c2009-02-04 17:27:36 +0000582 NamedDecl *D = 0;
Sebastian Redlcd965b92009-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 Gregor7176fff2009-01-15 00:26:24 +0000589 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000590
Chris Lattner8a934232008-03-31 00:36:02 +0000591 // If this reference is in an Objective-C method, then ivar lookup happens as
592 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000593 IdentifierInfo *II = Name.getAsIdentifierInfo();
594 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-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 Gregor4afa39d2009-01-20 01:17:11 +0000600 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000601 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000602 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000603 // Check if referencing a field with __attribute__((deprecated)).
604 DiagnoseUseOfDeprecatedDecl(IV, Loc);
605
Chris Lattner8a934232008-03-31 00:36:02 +0000606 // FIXME: This should use a new expr for a direct reference, don't turn
607 // this into Self->ivar, just return a BareIVarExpr or something.
608 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd965b92009-01-18 18:53:16 +0000609 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000610 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
611 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000612 true, true);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000613 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000614 return Owned(MRef);
Chris Lattner8a934232008-03-31 00:36:02 +0000615 }
616 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000617 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000618 if (D == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000619 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000620 getCurMethodDecl()->getClassInterface()));
Steve Naroff6ece14c2009-01-21 00:14:39 +0000621 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000622 }
Chris Lattner8a934232008-03-31 00:36:02 +0000623 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 if (D == 0) {
625 // Otherwise, this could be an implicitly declared function reference (legal
626 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000627 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000628 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000629 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 else {
631 // If this name wasn't predeclared and if this is not a function call,
632 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000633 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000634 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
635 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000636 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
637 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000638 return ExprError(Diag(Loc, diag::err_undeclared_use)
639 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000640 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000641 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 }
643 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000644
Sebastian Redlebc07d52009-02-03 20:19:35 +0000645 // If this is an expression of the form &Class::member, don't build an
646 // implicit member ref, because we want a pointer to the member in general,
647 // not any specific instance's member.
648 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000649 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000650 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000651 QualType DType;
652 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
653 DType = FD->getType().getNonReferenceType();
654 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
655 DType = Method->getType();
656 } else if (isa<OverloadedFunctionDecl>(D)) {
657 DType = Context.OverloadTy;
658 }
659 // Could be an inner type. That's diagnosed below, so ignore it here.
660 if (!DType.isNull()) {
661 // The pointer is type- and value-dependent if it points into something
662 // dependent.
663 bool Dependent = false;
664 for (; DC; DC = DC->getParent()) {
665 // FIXME: could stop early at namespace scope.
666 if (DC->isRecord()) {
667 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
668 if (Context.getTypeDeclType(Record)->isDependentType()) {
669 Dependent = true;
670 break;
671 }
672 }
673 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000674 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redlebc07d52009-02-03 20:19:35 +0000675 }
676 }
677 }
678
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000679 // We may have found a field within an anonymous union or struct
680 // (C++ [class.union]).
681 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
682 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
683 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000684
Douglas Gregor88a35142008-12-22 05:46:06 +0000685 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
686 if (!MD->isStatic()) {
687 // C++ [class.mfct.nonstatic]p2:
688 // [...] if name lookup (3.4.1) resolves the name in the
689 // id-expression to a nonstatic nontype member of class X or of
690 // a base class of X, the id-expression is transformed into a
691 // class member access expression (5.2.5) using (*this) (9.3.2)
692 // as the postfix-expression to the left of the '.' operator.
693 DeclContext *Ctx = 0;
694 QualType MemberType;
695 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
696 Ctx = FD->getDeclContext();
697 MemberType = FD->getType();
698
699 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
700 MemberType = RefType->getPointeeType();
701 else if (!FD->isMutable()) {
702 unsigned combinedQualifiers
703 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
704 MemberType = MemberType.getQualifiedType(combinedQualifiers);
705 }
706 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
707 if (!Method->isStatic()) {
708 Ctx = Method->getParent();
709 MemberType = Method->getType();
710 }
711 } else if (OverloadedFunctionDecl *Ovl
712 = dyn_cast<OverloadedFunctionDecl>(D)) {
713 for (OverloadedFunctionDecl::function_iterator
714 Func = Ovl->function_begin(),
715 FuncEnd = Ovl->function_end();
716 Func != FuncEnd; ++Func) {
717 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
718 if (!DMethod->isStatic()) {
719 Ctx = Ovl->getDeclContext();
720 MemberType = Context.OverloadTy;
721 break;
722 }
723 }
724 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000725
726 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000727 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
728 QualType ThisType = Context.getTagDeclType(MD->getParent());
729 if ((Context.getCanonicalType(CtxType)
730 == Context.getCanonicalType(ThisType)) ||
731 IsDerivedFrom(ThisType, CtxType)) {
732 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000733 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor88a35142008-12-22 05:46:06 +0000734 MD->getThisType(Context));
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000735 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd965b92009-01-18 18:53:16 +0000736 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000737 }
738 }
739 }
740 }
741
Douglas Gregor44b43212008-12-11 16:49:14 +0000742 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000743 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
744 if (MD->isStatic())
745 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000746 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
747 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000748 }
749
Douglas Gregor88a35142008-12-22 05:46:06 +0000750 // Any other ways we could have found the field in a well-formed
751 // program would have been turned into implicit member expressions
752 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000753 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
754 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000755 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000756
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000758 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000759 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000760 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000761 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000762 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000763
Steve Naroffdd972f22008-09-05 22:11:13 +0000764 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000765 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000766 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
767 false, false, SS));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000768 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
769 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
770 false, false, SS));
Steve Naroffdd972f22008-09-05 22:11:13 +0000771 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000772
Chris Lattner61a0f172009-02-15 01:38:09 +0000773 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner76a642f2009-02-15 22:43:40 +0000774 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattner61a0f172009-02-15 01:38:09 +0000775
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000776 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000777 // Warn about constructs like:
778 // if (void *X = foo()) { ... } else { X }.
779 // In the else block, the pointer is always false.
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000780 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
781 Scope *CheckS = S;
782 while (CheckS) {
783 if (CheckS->isWithinElse() &&
784 CheckS->getControlParent()->isDeclScope(Var)) {
785 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000786 ExprError(Diag(Loc, diag::warn_value_always_false)
787 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000788 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000789 ExprError(Diag(Loc, diag::warn_value_always_zero)
790 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000791 break;
792 }
793
794 // Move up one more control parent to check again.
795 CheckS = CheckS->getControlParent();
796 if (CheckS)
797 CheckS = CheckS->getParent();
798 }
799 }
800 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000801
802 // Only create DeclRefExpr's for valid Decl's.
803 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000804 return ExprError();
805
Chris Lattner639e2d32008-10-20 05:16:36 +0000806 // If the identifier reference is inside a block, and it refers to a value
807 // that is outside the block, create a BlockDeclRefExpr instead of a
808 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
809 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000810 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000811 // We do not do this for things like enum constants, global variables, etc,
812 // as they do not get snapshotted.
813 //
814 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000815 // The BlocksAttr indicates the variable is bound by-reference.
816 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000817 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000818 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000819
Steve Naroff090276f2008-10-10 01:28:17 +0000820 // Variable will be bound by-copy, make it const within the closure.
821 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000822 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000823 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000824 }
825 // If this reference is not in a block or if the referenced variable is
826 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000827
Douglas Gregor898574e2008-12-05 23:32:09 +0000828 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000829 bool ValueDependent = false;
830 if (getLangOptions().CPlusPlus) {
831 // C++ [temp.dep.expr]p3:
832 // An id-expression is type-dependent if it contains:
833 // - an identifier that was declared with a dependent type,
834 if (VD->getType()->isDependentType())
835 TypeDependent = true;
836 // - FIXME: a template-id that is dependent,
837 // - a conversion-function-id that specifies a dependent type,
838 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
839 Name.getCXXNameType()->isDependentType())
840 TypeDependent = true;
841 // - a nested-name-specifier that contains a class-name that
842 // names a dependent type.
843 else if (SS && !SS->isEmpty()) {
844 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
845 DC; DC = DC->getParent()) {
846 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000847 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000848 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
849 if (Context.getTypeDeclType(Record)->isDependentType()) {
850 TypeDependent = true;
851 break;
852 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000853 }
854 }
855 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000856
Douglas Gregor83f96f62008-12-10 20:57:37 +0000857 // C++ [temp.dep.constexpr]p2:
858 //
859 // An identifier is value-dependent if it is:
860 // - a name declared with a dependent type,
861 if (TypeDependent)
862 ValueDependent = true;
863 // - the name of a non-type template parameter,
864 else if (isa<NonTypeTemplateParmDecl>(VD))
865 ValueDependent = true;
866 // - a constant with integral or enumeration type and is
867 // initialized with an expression that is value-dependent
868 // (FIXME!).
869 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000870
Sebastian Redlcd965b92009-01-18 18:53:16 +0000871 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
872 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000873}
874
Sebastian Redlcd965b92009-01-18 18:53:16 +0000875Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
876 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000877 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000880 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000881 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
882 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
883 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000885
Chris Lattnerfa28b302008-01-12 08:14:25 +0000886 // Pre-defined identifiers are of type char[x], where x is the length of the
887 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000888 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000889 if (FunctionDecl *FD = getCurFunctionDecl())
890 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000891 else if (ObjCMethodDecl *MD = getCurMethodDecl())
892 Length = MD->getSynthesizedMethodSize();
893 else {
894 Diag(Loc, diag::ext_predef_outside_function);
895 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
896 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
897 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000898
899
Chris Lattner8f978d52008-01-12 19:32:28 +0000900 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000901 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000902 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000903 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +0000904}
905
Sebastian Redlcd965b92009-01-18 18:53:16 +0000906Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 llvm::SmallString<16> CharBuffer;
908 CharBuffer.resize(Tok.getLength());
909 const char *ThisTokBegin = &CharBuffer[0];
910 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000911
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
913 Tok.getLocation(), PP);
914 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000915 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000916
917 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
918
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000919 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
920 Literal.isWide(),
921 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000922}
923
Sebastian Redlcd965b92009-01-18 18:53:16 +0000924Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
925 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
927 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +0000928 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +0000929 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000930 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +0000931 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 }
Ted Kremenek28396602009-01-13 23:19:12 +0000933
Reid Spencer5f016e22007-07-11 17:01:13 +0000934 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000935 // Add padding so that NumericLiteralParser can overread by one character.
936 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +0000938
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 // Get the spelling of the token, which eliminates trigraphs, etc.
940 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000941
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
943 Tok.getLocation(), PP);
944 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000945 return ExprError();
946
Chris Lattner5d661452007-08-26 03:42:43 +0000947 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000948
Chris Lattner5d661452007-08-26 03:42:43 +0000949 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000950 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000951 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000952 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000953 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000954 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000955 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000956 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000957
958 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
959
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000960 // isExact will be set by GetFloatValue().
961 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000962 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
963 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +0000964
Chris Lattner5d661452007-08-26 03:42:43 +0000965 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000966 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +0000967 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000968 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000969
Neil Boothb9449512007-08-29 22:00:19 +0000970 // long long is a C99 feature.
971 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000972 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000973 Diag(Tok.getLocation(), diag::ext_longlong);
974
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000976 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000977
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 if (Literal.GetIntegerValue(ResultVal)) {
979 // If this value didn't fit into uintmax_t, warn and force to ull.
980 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000981 Ty = Context.UnsignedLongLongTy;
982 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000983 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 } else {
985 // If this value fits into a ULL, try to figure out what else it fits into
986 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000987
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 // Octal, Hexadecimal, and integers with a U suffix are allowed to
989 // be an unsigned int.
990 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
991
992 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000993 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000994 if (!Literal.isLong && !Literal.isLongLong) {
995 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000996 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000997
Reid Spencer5f016e22007-07-11 17:01:13 +0000998 // Does it fit in a unsigned int?
999 if (ResultVal.isIntN(IntSize)) {
1000 // Does it fit in a signed int?
1001 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001002 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001004 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001005 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001008
Reid Spencer5f016e22007-07-11 17:01:13 +00001009 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001010 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001011 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001012
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 // Does it fit in a unsigned long?
1014 if (ResultVal.isIntN(LongSize)) {
1015 // Does it fit in a signed long?
1016 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001017 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001019 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001020 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001022 }
1023
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001025 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001026 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001027
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 // Does it fit in a unsigned long long?
1029 if (ResultVal.isIntN(LongLongSize)) {
1030 // Does it fit in a signed long long?
1031 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001032 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001034 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001035 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 }
1037 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001038
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 // If we still couldn't decide a type, we probably have something that
1040 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001041 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001043 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001044 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001046
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001047 if (ResultVal.getBitWidth() != Width)
1048 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001050 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001052
Chris Lattner5d661452007-08-26 03:42:43 +00001053 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1054 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001055 Res = new (Context) ImaginaryLiteral(Res,
1056 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001057
1058 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001059}
1060
Sebastian Redlcd965b92009-01-18 18:53:16 +00001061Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1062 SourceLocation R, ExprArg Val) {
1063 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001064 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001065 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001066}
1067
1068/// The UsualUnaryConversions() function is *not* called by this routine.
1069/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +00001070bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1071 SourceLocation OpLoc,
1072 const SourceRange &ExprRange,
1073 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001075 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001077 if (isSizeof)
1078 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1079 return false;
1080 }
1081
1082 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001083 Diag(OpLoc, diag::ext_sizeof_void_type)
1084 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001085 return false;
1086 }
Sebastian Redl05189992008-11-11 17:56:53 +00001087
Chris Lattner01072922009-01-24 19:46:37 +00001088 return DiagnoseIncompleteType(OpLoc, exprType,
1089 isSizeof ? diag::err_sizeof_incomplete_type :
1090 diag::err_alignof_incomplete_type,
1091 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001092}
1093
Chris Lattner31e21e02009-01-24 20:17:12 +00001094bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1095 const SourceRange &ExprRange) {
1096 E = E->IgnoreParens();
1097
1098 // alignof decl is always ok.
1099 if (isa<DeclRefExpr>(E))
1100 return false;
1101
1102 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1103 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1104 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001105 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001106 return true;
1107 }
1108 // Other fields are ok.
1109 return false;
1110 }
1111 }
1112 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1113}
1114
Sebastian Redl05189992008-11-11 17:56:53 +00001115/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1116/// the same for @c alignof and @c __alignof
1117/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001118Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001119Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1120 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001122 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001123
Sebastian Redl05189992008-11-11 17:56:53 +00001124 QualType ArgTy;
1125 SourceRange Range;
1126 if (isType) {
1127 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1128 Range = ArgRange;
Chris Lattner694b1e42009-01-24 19:49:13 +00001129
1130 // Verify that the operand is valid.
1131 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1132 return ExprError();
Sebastian Redl05189992008-11-11 17:56:53 +00001133 } else {
1134 // Get the end location.
1135 Expr *ArgEx = (Expr *)TyOrEx;
1136 Range = ArgEx->getSourceRange();
1137 ArgTy = ArgEx->getType();
Chris Lattner694b1e42009-01-24 19:49:13 +00001138
1139 // Verify that the operand is valid.
Chris Lattner31e21e02009-01-24 20:17:12 +00001140 bool isInvalid;
Chris Lattnerda027472009-01-24 21:29:22 +00001141 if (!isSizeof) {
Chris Lattner31e21e02009-01-24 20:17:12 +00001142 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattnerda027472009-01-24 21:29:22 +00001143 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1144 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1145 isInvalid = true;
1146 } else {
1147 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1148 }
Chris Lattner31e21e02009-01-24 20:17:12 +00001149
1150 if (isInvalid) {
Chris Lattner694b1e42009-01-24 19:49:13 +00001151 DeleteExpr(ArgEx);
1152 return ExprError();
1153 }
Sebastian Redl05189992008-11-11 17:56:53 +00001154 }
1155
Sebastian Redl05189992008-11-11 17:56:53 +00001156 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001157 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner01072922009-01-24 19:46:37 +00001158 Context.getSizeType(), OpLoc,
1159 Range.getEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001160}
1161
Chris Lattner5d794252007-08-24 21:41:10 +00001162QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001163 DefaultFunctionArrayConversion(V);
1164
Chris Lattnercc26ed72007-08-26 05:39:26 +00001165 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001166 if (const ComplexType *CT = V->getType()->getAsComplexType())
1167 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001168
1169 // Otherwise they pass through real integer and floating point types here.
1170 if (V->getType()->isArithmeticType())
1171 return V->getType();
1172
1173 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001174 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001175 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001176}
1177
1178
Reid Spencer5f016e22007-07-11 17:01:13 +00001179
Sebastian Redl0eb23302009-01-19 00:08:26 +00001180Action::OwningExprResult
1181Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1182 tok::TokenKind Kind, ExprArg Input) {
1183 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001184
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 UnaryOperator::Opcode Opc;
1186 switch (Kind) {
1187 default: assert(0 && "Unknown unary op!");
1188 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1189 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1190 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001191
Douglas Gregor74253732008-11-19 15:42:04 +00001192 if (getLangOptions().CPlusPlus &&
1193 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1194 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001195 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001196 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1197
1198 // C++ [over.inc]p1:
1199 //
1200 // [...] If the function is a member function with one
1201 // parameter (which shall be of type int) or a non-member
1202 // function with two parameters (the second of which shall be
1203 // of type int), it defines the postfix increment operator ++
1204 // for objects of that type. When the postfix increment is
1205 // called as a result of using the ++ operator, the int
1206 // argument will have value zero.
1207 Expr *Args[2] = {
1208 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001209 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1210 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001211 };
1212
1213 // Build the candidate set for overloading
1214 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001215 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1216 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001217
1218 // Perform overload resolution.
1219 OverloadCandidateSet::iterator Best;
1220 switch (BestViableFunction(CandidateSet, Best)) {
1221 case OR_Success: {
1222 // We found a built-in operator or an overloaded operator.
1223 FunctionDecl *FnDecl = Best->Function;
1224
1225 if (FnDecl) {
1226 // We matched an overloaded operator. Build a call to that
1227 // operator.
1228
1229 // Convert the arguments.
1230 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1231 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001232 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001233 } else {
1234 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001235 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001236 FnDecl->getParamDecl(0)->getType(),
1237 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001238 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001239 }
1240
1241 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001242 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001243 = FnDecl->getType()->getAsFunctionType()->getResultType();
1244 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001245
Douglas Gregor74253732008-11-19 15:42:04 +00001246 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001247 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor74253732008-11-19 15:42:04 +00001248 SourceLocation());
1249 UsualUnaryConversions(FnExpr);
1250
Sebastian Redl0eb23302009-01-19 00:08:26 +00001251 Input.release();
Ted Kremenek668bf912009-02-09 20:51:47 +00001252 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1253 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001254 } else {
1255 // We matched a built-in operator. Convert the arguments, then
1256 // break out so that we will build the appropriate built-in
1257 // operator node.
1258 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1259 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001260 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001261
1262 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001263 }
Douglas Gregor74253732008-11-19 15:42:04 +00001264 }
1265
1266 case OR_No_Viable_Function:
1267 // No viable function; fall through to handling this as a
1268 // built-in operator, which will produce an error message for us.
1269 break;
1270
1271 case OR_Ambiguous:
1272 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1273 << UnaryOperator::getOpcodeStr(Opc)
1274 << Arg->getSourceRange();
1275 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001276 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001277 }
1278
1279 // Either we found no viable overloaded operator or we matched a
1280 // built-in operator. In either case, fall through to trying to
1281 // build a built-in operation.
1282 }
1283
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001284 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1285 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001287 return ExprError();
1288 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001289 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001290}
1291
Sebastian Redl0eb23302009-01-19 00:08:26 +00001292Action::OwningExprResult
1293Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1294 ExprArg Idx, SourceLocation RLoc) {
1295 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1296 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001297
Douglas Gregor337c6b92008-11-19 17:17:41 +00001298 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001299 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001300 LHSExp->getType()->isEnumeralType() ||
1301 RHSExp->getType()->isRecordType() ||
1302 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001303 // Add the appropriate overloaded operators (C++ [over.match.oper])
1304 // to the candidate set.
1305 OverloadCandidateSet CandidateSet;
1306 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001307 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1308 SourceRange(LLoc, RLoc)))
1309 return ExprError();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001310
Douglas Gregor337c6b92008-11-19 17:17:41 +00001311 // Perform overload resolution.
1312 OverloadCandidateSet::iterator Best;
1313 switch (BestViableFunction(CandidateSet, Best)) {
1314 case OR_Success: {
1315 // We found a built-in operator or an overloaded operator.
1316 FunctionDecl *FnDecl = Best->Function;
1317
1318 if (FnDecl) {
1319 // We matched an overloaded operator. Build a call to that
1320 // operator.
1321
1322 // Convert the arguments.
1323 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1324 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1325 PerformCopyInitialization(RHSExp,
1326 FnDecl->getParamDecl(0)->getType(),
1327 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001328 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001329 } else {
1330 // Convert the arguments.
1331 if (PerformCopyInitialization(LHSExp,
1332 FnDecl->getParamDecl(0)->getType(),
1333 "passing") ||
1334 PerformCopyInitialization(RHSExp,
1335 FnDecl->getParamDecl(1)->getType(),
1336 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001337 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001338 }
1339
1340 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001341 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001342 = FnDecl->getType()->getAsFunctionType()->getResultType();
1343 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001344
Douglas Gregor337c6b92008-11-19 17:17:41 +00001345 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001346 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor337c6b92008-11-19 17:17:41 +00001347 SourceLocation());
1348 UsualUnaryConversions(FnExpr);
1349
Sebastian Redl0eb23302009-01-19 00:08:26 +00001350 Base.release();
1351 Idx.release();
Ted Kremenek668bf912009-02-09 20:51:47 +00001352 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001353 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001354 } else {
1355 // We matched a built-in operator. Convert the arguments, then
1356 // break out so that we will build the appropriate built-in
1357 // operator node.
1358 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1359 "passing") ||
1360 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1361 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001362 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001363
1364 break;
1365 }
1366 }
1367
1368 case OR_No_Viable_Function:
1369 // No viable function; fall through to handling this as a
1370 // built-in operator, which will produce an error message for us.
1371 break;
1372
1373 case OR_Ambiguous:
1374 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1375 << "[]"
1376 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1377 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001378 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001379 }
1380
1381 // Either we found no viable overloaded operator or we matched a
1382 // built-in operator. In either case, fall through to trying to
1383 // build a built-in operation.
1384 }
1385
Chris Lattner12d9ff62007-07-16 00:14:47 +00001386 // Perform default conversions.
1387 DefaultFunctionArrayConversion(LHSExp);
1388 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001389
Chris Lattner12d9ff62007-07-16 00:14:47 +00001390 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001391
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001393 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // in the subscript position. As a result, we need to derive the array base
1395 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001396 Expr *BaseExpr, *IndexExpr;
1397 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001398 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001399 BaseExpr = LHSExp;
1400 IndexExpr = RHSExp;
1401 // FIXME: need to deal with const...
1402 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001403 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001404 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001405 BaseExpr = RHSExp;
1406 IndexExpr = LHSExp;
1407 // FIXME: need to deal with const...
1408 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001409 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1410 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001411 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001412
Chris Lattner12d9ff62007-07-16 00:14:47 +00001413 // FIXME: need to deal with const...
1414 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001416 return ExprError(Diag(LHSExp->getLocStart(),
1417 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1418 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001420 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001421 return ExprError(Diag(IndexExpr->getLocStart(),
1422 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001423
Chris Lattner12d9ff62007-07-16 00:14:47 +00001424 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1425 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001426 // void (*)(int)) and pointers to incomplete types. Functions are not
1427 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001428 if (!ResultType->isObjectType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001429 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001430 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001431 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001432
Sebastian Redl0eb23302009-01-19 00:08:26 +00001433 Base.release();
1434 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001435 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1436 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001437}
1438
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001439QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001440CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001441 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001442 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001443
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001444 // The vector accessor can't exceed the number of elements.
1445 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001446
1447 // This flag determines whether or not the component is one of the four
1448 // special names that indicate a subset of exactly half the elements are
1449 // to be selected.
1450 bool HalvingSwizzle = false;
1451
1452 // This flag determines whether or not CompName has an 's' char prefix,
1453 // indicating that it is a string of hex values to be used as vector indices.
1454 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001455
1456 // Check that we've found one of the special components, or that the component
1457 // names must come from the same set.
1458 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001459 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1460 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001461 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001462 do
1463 compStr++;
1464 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001465 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001466 do
1467 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001468 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001469 }
Nate Begeman353417a2009-01-18 01:47:54 +00001470
1471 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001472 // We didn't get to the end of the string. This means the component names
1473 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001474 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1475 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001476 return QualType();
1477 }
Nate Begeman353417a2009-01-18 01:47:54 +00001478
1479 // Ensure no component accessor exceeds the width of the vector type it
1480 // operates on.
1481 if (!HalvingSwizzle) {
1482 compStr = CompName.getName();
1483
1484 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001485 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001486
1487 while (*compStr) {
1488 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1489 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1490 << baseType << SourceRange(CompLoc);
1491 return QualType();
1492 }
1493 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001494 }
Nate Begeman8a997642008-05-09 06:41:27 +00001495
Nate Begeman353417a2009-01-18 01:47:54 +00001496 // If this is a halving swizzle, verify that the base type has an even
1497 // number of elements.
1498 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001499 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001500 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001501 return QualType();
1502 }
1503
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001504 // The component accessor looks fine - now we need to compute the actual type.
1505 // The vector type is implied by the component accessor. For example,
1506 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001507 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001508 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001509 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1510 : CompName.getLength();
1511 if (HexSwizzle)
1512 CompSize--;
1513
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001514 if (CompSize == 1)
1515 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001516
Nate Begeman213541a2008-04-18 23:10:10 +00001517 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001518 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001519 // diagostics look bad. We want extended vector types to appear built-in.
1520 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1521 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1522 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001523 }
1524 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001525}
1526
Chris Lattner76a642f2009-02-15 22:43:40 +00001527
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001528/// constructSetterName - Return the setter name for the given
1529/// identifier, i.e. "set" + Name where the initial character of Name
1530/// has been capitalized.
1531// FIXME: Merge with same routine in Parser. But where should this
1532// live?
1533static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1534 const IdentifierInfo *Name) {
1535 llvm::SmallString<100> SelectorName;
1536 SelectorName = "set";
1537 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1538 SelectorName[3] = toupper(SelectorName[3]);
1539 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1540}
1541
Sebastian Redl0eb23302009-01-19 00:08:26 +00001542Action::OwningExprResult
1543Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1544 tok::TokenKind OpKind, SourceLocation MemberLoc,
1545 IdentifierInfo &Member) {
1546 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001547 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001548
1549 // Perform default conversions.
1550 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001551
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001552 QualType BaseType = BaseExpr->getType();
1553 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001554
Chris Lattner68a057b2008-07-21 04:36:39 +00001555 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1556 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001558 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001559 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001560 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001561 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1562 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001563 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001564 return ExprError(Diag(MemberLoc,
1565 diag::err_typecheck_member_reference_arrow)
1566 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001568
Chris Lattner68a057b2008-07-21 04:36:39 +00001569 // Handle field access to simple records. This also handles access to fields
1570 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001571 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001572 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001573 if (DiagnoseIncompleteType(OpLoc, BaseType,
1574 diag::err_typecheck_incomplete_tag,
1575 BaseExpr->getSourceRange()))
1576 return ExprError();
1577
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001578 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001579 // FIXME: Qualified name lookup for C++ is a bit more complicated
1580 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001581 LookupResult Result
Douglas Gregor7176fff2009-01-15 00:26:24 +00001582 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001583 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001584
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001585 NamedDecl *MemberDecl = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001586 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001587 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1588 << &Member << BaseExpr->getSourceRange());
1589 else if (Result.isAmbiguous()) {
1590 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1591 MemberLoc, BaseExpr->getSourceRange());
1592 return ExprError();
1593 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001594 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001595
Chris Lattner56cd21b2009-02-13 22:08:30 +00001596 // If the decl being referenced had an error, return an error for this
1597 // sub-expr without emitting another error, in order to avoid cascading
1598 // error cases.
1599 if (MemberDecl->isInvalidDecl())
1600 return ExprError();
Chris Lattnercfdff382009-02-16 17:07:21 +00001601
1602 // Check if referencing a field with __attribute__((deprecated)).
1603 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattner56cd21b2009-02-13 22:08:30 +00001604
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001605 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001606 // We may have found a field within an anonymous union or struct
1607 // (C++ [class.union]).
1608 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001609 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001610 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001611
Douglas Gregor86f19402008-12-20 23:49:58 +00001612 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1613 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001614 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001615 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1616 MemberType = Ref->getPointeeType();
1617 else {
1618 unsigned combinedQualifiers =
1619 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001620 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001621 combinedQualifiers &= ~QualType::Const;
1622 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1623 }
Eli Friedman51019072008-02-06 22:48:16 +00001624
Steve Naroff6ece14c2009-01-21 00:14:39 +00001625 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1626 MemberLoc, MemberType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001627 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001628 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001629 Var, MemberLoc,
1630 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001631 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001632 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1633 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001634 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001635 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001636 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001637 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001638 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001639 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001640 MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001641 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001642 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1643 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001644
Douglas Gregor86f19402008-12-20 23:49:58 +00001645 // We found a declaration kind that we didn't expect. This is a
1646 // generic error message that tells the user that she can't refer
1647 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001648 return ExprError(Diag(MemberLoc,
1649 diag::err_typecheck_member_reference_unknown)
1650 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001651 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001652
Chris Lattnera38e6b12008-07-21 04:59:05 +00001653 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1654 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001655 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001656 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattner56cd21b2009-02-13 22:08:30 +00001657 // If the decl being referenced had an error, return an error for this
1658 // sub-expr without emitting another error, in order to avoid cascading
1659 // error cases.
1660 if (IV->isInvalidDecl())
1661 return ExprError();
1662
Chris Lattner553905d2009-02-16 17:19:12 +00001663 // Check if referencing a field with __attribute__((deprecated)).
1664 DiagnoseUseOfDeprecatedDecl(IV, MemberLoc);
1665
Steve Naroff6ece14c2009-01-21 00:14:39 +00001666 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1667 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001668 OpKind == tok::arrow);
1669 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001670 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001671 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001672 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1673 << IFTy->getDecl()->getDeclName() << &Member
1674 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001675 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001676
Chris Lattnera38e6b12008-07-21 04:59:05 +00001677 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1678 // pointer to a (potentially qualified) interface type.
1679 const PointerType *PTy;
1680 const ObjCInterfaceType *IFTy;
1681 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1682 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1683 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001684
Daniel Dunbar2307d312008-09-03 01:05:41 +00001685 // Search for a declared property first.
Chris Lattner7eba82e2009-02-16 18:35:08 +00001686 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1687 // Check if referencing a property with __attribute__((deprecated)).
1688 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1689
Steve Naroff6ece14c2009-01-21 00:14:39 +00001690 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001691 MemberLoc, BaseExpr));
1692 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001693
Daniel Dunbar2307d312008-09-03 01:05:41 +00001694 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001695 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1696 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner7eba82e2009-02-16 18:35:08 +00001697 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1698 // Check if referencing a property with __attribute__((deprecated)).
1699 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1700
Steve Naroff6ece14c2009-01-21 00:14:39 +00001701 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001702 MemberLoc, BaseExpr));
1703 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001704
1705 // If that failed, look for an "implicit" property by seeing if the nullary
1706 // selector is implemented.
1707
1708 // FIXME: The logic for looking up nullary and unary selectors should be
1709 // shared with the code in ActOnInstanceMessage.
1710
1711 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1712 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001713
Daniel Dunbar2307d312008-09-03 01:05:41 +00001714 // If this reference is in an @implementation, check for 'private' methods.
1715 if (!Getter)
1716 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1717 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1718 if (ObjCImplementationDecl *ImpDecl =
1719 ObjCImplementations[ClassDecl->getIdentifier()])
1720 Getter = ImpDecl->getInstanceMethod(Sel);
1721
Steve Naroff7692ed62008-10-22 19:16:27 +00001722 // Look through local category implementations associated with the class.
1723 if (!Getter) {
1724 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1725 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1726 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1727 }
1728 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001729 if (Getter) {
Chris Lattner7eba82e2009-02-16 18:35:08 +00001730 // Check if referencing a property with __attribute__((deprecated)).
1731 DiagnoseUseOfDeprecatedDecl(Getter, MemberLoc);
1732
Daniel Dunbar2307d312008-09-03 01:05:41 +00001733 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001734 // will look for the matching setter, in case it is needed.
1735 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1736 &Member);
1737 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1738 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1739 if (!Setter) {
1740 // If this reference is in an @implementation, also check for 'private'
1741 // methods.
1742 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1743 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1744 if (ObjCImplementationDecl *ImpDecl =
1745 ObjCImplementations[ClassDecl->getIdentifier()])
1746 Setter = ImpDecl->getInstanceMethod(SetterSel);
1747 }
1748 // Look through local category implementations associated with the class.
1749 if (!Setter) {
1750 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1751 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1752 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1753 }
1754 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001755
Chris Lattner7eba82e2009-02-16 18:35:08 +00001756 if (Setter)
1757 // Check if referencing a property with __attribute__((deprecated)).
1758 DiagnoseUseOfDeprecatedDecl(Setter, MemberLoc);
1759
1760
Sebastian Redl0eb23302009-01-19 00:08:26 +00001761 // FIXME: we must check that the setter has property type.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001762 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1763 Setter, MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001764 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001765
1766 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1767 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001768 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001769 // Handle properties on qualified "id" protocols.
1770 const ObjCQualifiedIdType *QIdTy;
1771 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1772 // Check protocols on qualified interfaces.
1773 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001774 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner7eba82e2009-02-16 18:35:08 +00001775 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1776 // Check if referencing a property with __attribute__((deprecated)).
1777 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1778
Steve Naroff6ece14c2009-01-21 00:14:39 +00001779 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001780 MemberLoc, BaseExpr));
1781 }
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001782 // Also must look for a getter name which uses property syntax.
1783 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1784 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Chris Lattner7eba82e2009-02-16 18:35:08 +00001785 // Check if referencing a property with __attribute__((deprecated)).
1786 DiagnoseUseOfDeprecatedDecl(OMD, MemberLoc);
1787
Steve Naroff6ece14c2009-01-21 00:14:39 +00001788 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1789 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001790 }
1791 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001792
1793 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1794 << &Member << BaseType);
1795 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001796 // Handle 'field access' to vectors, such as 'V.xx'.
1797 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001798 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1799 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001800 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001801 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1802 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001803 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001804
1805 return ExprError(Diag(MemberLoc,
1806 diag::err_typecheck_member_reference_struct_union)
1807 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001808}
1809
Douglas Gregor88a35142008-12-22 05:46:06 +00001810/// ConvertArgumentsForCall - Converts the arguments specified in
1811/// Args/NumArgs to the parameter types of the function FDecl with
1812/// function prototype Proto. Call is the call expression itself, and
1813/// Fn is the function expression. For a C++ member function, this
1814/// routine does not attempt to convert the object argument. Returns
1815/// true if the call is ill-formed.
1816bool
1817Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1818 FunctionDecl *FDecl,
1819 const FunctionTypeProto *Proto,
1820 Expr **Args, unsigned NumArgs,
1821 SourceLocation RParenLoc) {
1822 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1823 // assignment, to the types of the corresponding parameter, ...
1824 unsigned NumArgsInProto = Proto->getNumArgs();
1825 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001826 bool Invalid = false;
1827
Douglas Gregor88a35142008-12-22 05:46:06 +00001828 // If too few arguments are available (and we don't have default
1829 // arguments for the remaining parameters), don't make the call.
1830 if (NumArgs < NumArgsInProto) {
1831 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1832 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1833 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1834 // Use default arguments for missing arguments
1835 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001836 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00001837 }
1838
1839 // If too many are passed and not variadic, error on the extras and drop
1840 // them.
1841 if (NumArgs > NumArgsInProto) {
1842 if (!Proto->isVariadic()) {
1843 Diag(Args[NumArgsInProto]->getLocStart(),
1844 diag::err_typecheck_call_too_many_args)
1845 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1846 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1847 Args[NumArgs-1]->getLocEnd());
1848 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001849 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001850 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00001851 }
1852 NumArgsToCheck = NumArgsInProto;
1853 }
1854
1855 // Continue to check argument types (even if we have too few/many args).
1856 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1857 QualType ProtoArgType = Proto->getArgType(i);
1858
1859 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001860 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001861 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001862
1863 // Pass the argument.
1864 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1865 return true;
1866 } else
1867 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001868 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00001869 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001870
Douglas Gregor88a35142008-12-22 05:46:06 +00001871 Call->setArg(i, Arg);
1872 }
1873
1874 // If this is a variadic call, handle args passed through "...".
1875 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001876 VariadicCallType CallType = VariadicFunction;
1877 if (Fn->getType()->isBlockPointerType())
1878 CallType = VariadicBlock; // Block
1879 else if (isa<MemberExpr>(Fn))
1880 CallType = VariadicMethod;
1881
Douglas Gregor88a35142008-12-22 05:46:06 +00001882 // Promote the arguments (C99 6.5.2.2p7).
1883 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1884 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001885 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001886 Call->setArg(i, Arg);
1887 }
1888 }
1889
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001890 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00001891}
1892
Steve Narofff69936d2007-09-16 03:34:24 +00001893/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001894/// This provides the location of the left/right parens and a list of comma
1895/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001896Action::OwningExprResult
1897Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1898 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00001899 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001900 unsigned NumArgs = args.size();
1901 Expr *Fn = static_cast<Expr *>(fn.release());
1902 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00001903 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001904 FunctionDecl *FDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00001905 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00001906
Douglas Gregor88a35142008-12-22 05:46:06 +00001907 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00001908 // Determine whether this is a dependent call inside a C++ template,
1909 // in which case we won't do any semantic analysis now.
1910 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1911 bool Dependent = false;
1912 if (Fn->isTypeDependent())
1913 Dependent = true;
1914 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1915 Dependent = true;
1916
1917 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00001918 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00001919 Context.DependentTy, RParenLoc));
1920
1921 // Determine whether this is a call to an object (C++ [over.call.object]).
1922 if (Fn->getType()->isRecordType())
1923 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1924 CommaLocs, RParenLoc));
1925
Douglas Gregorfa047642009-02-04 00:32:51 +00001926 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00001927 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1928 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1929 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001930 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1931 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001932 }
1933
Douglas Gregorfa047642009-02-04 00:32:51 +00001934 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001935 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00001936 Expr *FnExpr = Fn;
1937 bool ADL = true;
1938 while (true) {
1939 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1940 FnExpr = IcExpr->getSubExpr();
1941 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor17330012009-02-04 15:01:18 +00001942 // Parentheses around a function disable ADL
1943 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00001944 ADL = false;
1945 FnExpr = PExpr->getSubExpr();
1946 } else if (isa<UnaryOperator>(FnExpr) &&
1947 cast<UnaryOperator>(FnExpr)->getOpcode()
1948 == UnaryOperator::AddrOf) {
1949 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattner90e150d2009-02-14 07:22:29 +00001950 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1951 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1952 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1953 break;
1954 } else if (UnresolvedFunctionNameExpr *DepName
1955 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1956 UnqualifiedName = DepName->getName();
1957 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00001958 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00001959 // Any kind of name that does not refer to a declaration (or
1960 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1961 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00001962 break;
1963 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001964 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001965
Douglas Gregor17330012009-02-04 15:01:18 +00001966 OverloadedFunctionDecl *Ovl = 0;
1967 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001968 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00001969 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1970 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001971
Douglas Gregorf9201e02009-02-11 23:02:49 +00001972 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001973 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00001974 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00001975 ADL = false;
1976
Douglas Gregorf9201e02009-02-11 23:02:49 +00001977 // We don't perform ADL in C.
1978 if (!getLangOptions().CPlusPlus)
1979 ADL = false;
1980
Douglas Gregor17330012009-02-04 15:01:18 +00001981 if (Ovl || ADL) {
1982 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1983 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00001984 NumArgs, CommaLocs, RParenLoc, ADL);
1985 if (!FDecl)
1986 return ExprError();
1987
1988 // Update Fn to refer to the actual function selected.
1989 Expr *NewFn = 0;
1990 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00001991 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregorfa047642009-02-04 00:32:51 +00001992 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1993 QDRExpr->getLocation(),
1994 false, false,
1995 QDRExpr->getSourceRange().getBegin());
1996 else
1997 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1998 Fn->getSourceRange().getBegin());
1999 Fn->Destroy(Context);
2000 Fn = NewFn;
2001 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002002 }
Chris Lattner04421082008-04-08 04:40:51 +00002003
2004 // Promote the function operand.
2005 UsualUnaryConversions(Fn);
2006
Chris Lattner925e60d2007-12-28 05:29:59 +00002007 // Make the call expr early, before semantic checks. This guarantees cleanup
2008 // of arguments and function on error.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002009 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
2010 // Destroy(), or nothing gets cleaned up.
Ted Kremenek668bf912009-02-09 20:51:47 +00002011 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2012 Args, NumArgs,
2013 Context.BoolTy,
2014 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002015
Steve Naroffdd972f22008-09-05 22:11:13 +00002016 const FunctionType *FuncT;
2017 if (!Fn->getType()->isBlockPointerType()) {
2018 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2019 // have type pointer to function".
2020 const PointerType *PT = Fn->getType()->getAsPointerType();
2021 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002022 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2023 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002024 FuncT = PT->getPointeeType()->getAsFunctionType();
2025 } else { // This is a block call.
2026 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2027 getAsFunctionType();
2028 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002029 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002030 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2031 << Fn->getType() << Fn->getSourceRange());
2032
Chris Lattner925e60d2007-12-28 05:29:59 +00002033 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002034 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002035
Chris Lattner925e60d2007-12-28 05:29:59 +00002036 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002037 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2038 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002039 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002040 } else {
2041 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002042
Steve Naroffb291ab62007-08-28 23:30:39 +00002043 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002044 for (unsigned i = 0; i != NumArgs; i++) {
2045 Expr *Arg = Args[i];
2046 DefaultArgumentPromotion(Arg);
2047 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002048 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002050
Douglas Gregor88a35142008-12-22 05:46:06 +00002051 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2052 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002053 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2054 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002055
Chris Lattner59907c42007-08-10 20:18:51 +00002056 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00002057 if (FDecl)
2058 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00002059
Sebastian Redl0eb23302009-01-19 00:08:26 +00002060 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002061}
2062
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002063Action::OwningExprResult
2064Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2065 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002066 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002067 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002068 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002069 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002070 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002071
Eli Friedman6223c222008-05-20 05:22:08 +00002072 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002073 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002074 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2075 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002076 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2077 diag::err_typecheck_decl_incomplete_type,
2078 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002079 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002080
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002081 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002082 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002083 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002084
Chris Lattner371f2582008-12-04 23:50:19 +00002085 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002086 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002087 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002088 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002089 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002090 InitExpr.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002091 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2092 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002093}
2094
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002095Action::OwningExprResult
2096Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2097 InitListDesignations &Designators,
2098 SourceLocation RBraceLoc) {
2099 unsigned NumInit = initlist.size();
2100 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002101
Steve Naroff08d92e42007-09-15 18:49:24 +00002102 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00002103 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002104
Steve Naroff6ece14c2009-01-21 00:14:39 +00002105 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002106 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002107 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002108 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002109}
2110
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002111/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002112bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002113 UsualUnaryConversions(castExpr);
2114
2115 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2116 // type needs to be scalar.
2117 if (castType->isVoidType()) {
2118 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002119 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2120 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002121 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002122 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2123 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2124 (castType->isStructureType() || castType->isUnionType())) {
2125 // GCC struct/union extension: allow cast to self.
2126 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2127 << castType << castExpr->getSourceRange();
2128 } else if (castType->isUnionType()) {
2129 // GCC cast to union extension
2130 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2131 RecordDecl::field_iterator Field, FieldEnd;
2132 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2133 Field != FieldEnd; ++Field) {
2134 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2135 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2136 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2137 << castExpr->getSourceRange();
2138 break;
2139 }
2140 }
2141 if (Field == FieldEnd)
2142 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2143 << castExpr->getType() << castExpr->getSourceRange();
2144 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002145 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002146 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002147 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002148 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002149 } else if (!castExpr->getType()->isScalarType() &&
2150 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002151 return Diag(castExpr->getLocStart(),
2152 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002153 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002154 } else if (castExpr->getType()->isVectorType()) {
2155 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2156 return true;
2157 } else if (castType->isVectorType()) {
2158 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2159 return true;
2160 }
2161 return false;
2162}
2163
Chris Lattnerfe23e212007-12-20 00:44:32 +00002164bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002165 assert(VectorTy->isVectorType() && "Not a vector type!");
2166
2167 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002168 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002169 return Diag(R.getBegin(),
2170 Ty->isVectorType() ?
2171 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002172 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002173 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002174 } else
2175 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002176 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002177 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002178
2179 return false;
2180}
2181
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002182Action::OwningExprResult
2183Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2184 SourceLocation RParenLoc, ExprArg Op) {
2185 assert((Ty != 0) && (Op.get() != 0) &&
2186 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002187
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002188 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002189 QualType castType = QualType::getFromOpaquePtr(Ty);
2190
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002191 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002192 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002193 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002194 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002195}
2196
Chris Lattnera21ddb32007-11-26 01:40:58 +00002197/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2198/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00002199inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00002200 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002201 UsualUnaryConversions(cond);
2202 UsualUnaryConversions(lex);
2203 UsualUnaryConversions(rex);
2204 QualType condT = cond->getType();
2205 QualType lexT = lex->getType();
2206 QualType rexT = rex->getType();
2207
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00002209 if (!cond->isTypeDependent()) {
2210 if (!condT->isScalarType()) { // C99 6.5.15p2
2211 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2212 return QualType();
2213 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002215
2216 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00002217 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2218 return Context.DependentTy;
2219
Chris Lattner70d67a92008-01-06 22:42:25 +00002220 // If both operands have arithmetic type, do the usual arithmetic conversions
2221 // to find a common type: C99 6.5.15p3,5.
2222 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00002223 UsualArithmeticConversions(lex, rex);
2224 return lex->getType();
2225 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002226
2227 // If both operands are the same structure or union type, the result is that
2228 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002229 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00002230 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002231 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002232 // "If both the operands have structure or union type, the result has
2233 // that type." This implies that CV qualifiers are dropped.
2234 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002235 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002236
2237 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002238 // The following || allows only one side to be void (a GCC-ism).
2239 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002240 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002241 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2242 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002243 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002244 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2245 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002246 ImpCastExprToType(lex, Context.VoidTy);
2247 ImpCastExprToType(rex, Context.VoidTy);
2248 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002249 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002250 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2251 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002252 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2253 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002254 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002255 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002256 return lexT;
2257 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002258 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2259 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002260 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002261 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002262 return rexT;
2263 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002264 // Handle the case where both operands are pointers before we handle null
2265 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002266 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2267 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2268 // get the "pointed to" types
2269 QualType lhptee = LHSPT->getPointeeType();
2270 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002271
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002272 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2273 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002274 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002275 // Figure out necessary qualifiers (C99 6.5.15p6)
2276 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002277 QualType destType = Context.getPointerType(destPointee);
2278 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2279 ImpCastExprToType(rex, destType); // promote to void*
2280 return destType;
2281 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002282 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002283 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002284 QualType destType = Context.getPointerType(destPointee);
2285 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2286 ImpCastExprToType(rex, destType); // promote to void*
2287 return destType;
2288 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002289
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002290 QualType compositeType = lexT;
2291
2292 // If either type is an Objective-C object type then check
2293 // compatibility according to Objective-C.
2294 if (Context.isObjCObjectPointerType(lexT) ||
2295 Context.isObjCObjectPointerType(rexT)) {
2296 // If both operands are interfaces and either operand can be
2297 // assigned to the other, use that type as the composite
2298 // type. This allows
2299 // xxx ? (A*) a : (B*) b
2300 // where B is a subclass of A.
2301 //
2302 // Additionally, as for assignment, if either type is 'id'
2303 // allow silent coercion. Finally, if the types are
2304 // incompatible then make sure to use 'id' as the composite
2305 // type so the result is acceptable for sending messages to.
2306
Steve Naroff1fd03612009-02-12 19:05:07 +00002307 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2308 // It could return the composite type.
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002309 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2310 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2311 if (LHSIface && RHSIface &&
2312 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2313 compositeType = lexT;
2314 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002315 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002316 compositeType = rexT;
Steve Naroff389bf462009-02-12 17:52:19 +00002317 } else if (Context.isObjCIdStructType(lhptee) ||
2318 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002319 compositeType = Context.getObjCIdType();
2320 } else {
Steve Naroff1fd03612009-02-12 19:05:07 +00002321 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2322 << lexT << rexT
2323 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002324 QualType incompatTy = Context.getObjCIdType();
2325 ImpCastExprToType(lex, incompatTy);
2326 ImpCastExprToType(rex, incompatTy);
2327 return incompatTy;
2328 }
2329 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2330 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002331 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002332 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002333 // In this situation, we assume void* type. No especially good
2334 // reason, but this is what gcc does, and we do have to pick
2335 // to get a consistent AST.
2336 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002337 ImpCastExprToType(lex, incompatTy);
2338 ImpCastExprToType(rex, incompatTy);
2339 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002340 }
2341 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002342 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2343 // differently qualified versions of compatible types, the result type is
2344 // a pointer to an appropriately qualified version of the *composite*
2345 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002346 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002347 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002348 ImpCastExprToType(lex, compositeType);
2349 ImpCastExprToType(rex, compositeType);
2350 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 }
2352 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002353 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2354 // evaluates to "struct objc_object *" (and is handled above when comparing
2355 // id with statically typed objects).
2356 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2357 // GCC allows qualified id and any Objective-C type to devolve to
2358 // id. Currently localizing to here until clear this should be
2359 // part of ObjCQualifiedIdTypesAreCompatible.
2360 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2361 (lexT->isObjCQualifiedIdType() &&
2362 Context.isObjCObjectPointerType(rexT)) ||
2363 (rexT->isObjCQualifiedIdType() &&
2364 Context.isObjCObjectPointerType(lexT))) {
2365 // FIXME: This is not the correct composite type. This only
2366 // happens to work because id can more or less be used anywhere,
2367 // however this may change the type of method sends.
2368 // FIXME: gcc adds some type-checking of the arguments and emits
2369 // (confusing) incompatible comparison warnings in some
2370 // cases. Investigate.
2371 QualType compositeType = Context.getObjCIdType();
2372 ImpCastExprToType(lex, compositeType);
2373 ImpCastExprToType(rex, compositeType);
2374 return compositeType;
2375 }
2376 }
2377
Steve Naroff61f40a22008-09-10 19:17:48 +00002378 // Selection between block pointer types is ok as long as they are the same.
2379 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2380 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2381 return lexT;
2382
Chris Lattner70d67a92008-01-06 22:42:25 +00002383 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002384 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002385 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002386 return QualType();
2387}
2388
Steve Narofff69936d2007-09-16 03:34:24 +00002389/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002390/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002391Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2392 SourceLocation ColonLoc,
2393 ExprArg Cond, ExprArg LHS,
2394 ExprArg RHS) {
2395 Expr *CondExpr = (Expr *) Cond.get();
2396 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002397
2398 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2399 // was the condition.
2400 bool isLHSNull = LHSExpr == 0;
2401 if (isLHSNull)
2402 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002403
2404 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002405 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002407 return ExprError();
2408
2409 Cond.release();
2410 LHS.release();
2411 RHS.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002412 return Owned(new (Context) ConditionalOperator(CondExpr,
2413 isLHSNull ? 0 : LHSExpr,
2414 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002415}
2416
Reid Spencer5f016e22007-07-11 17:01:13 +00002417
2418// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2419// being closely modeled after the C99 spec:-). The odd characteristic of this
2420// routine is it effectively iqnores the qualifiers on the top level pointee.
2421// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2422// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002423Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002424Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2425 QualType lhptee, rhptee;
2426
2427 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002428 lhptee = lhsType->getAsPointerType()->getPointeeType();
2429 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002430
2431 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002432 lhptee = Context.getCanonicalType(lhptee);
2433 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002434
Chris Lattner5cf216b2008-01-04 18:04:52 +00002435 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002436
2437 // C99 6.5.16.1p1: This following citation is common to constraints
2438 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2439 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002440 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002441 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002442 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002443
2444 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2445 // incomplete type and the other is a pointer to a qualified or unqualified
2446 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002447 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002448 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002449 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002450
2451 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002452 assert(rhptee->isFunctionType());
2453 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002454 }
2455
2456 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002457 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002458 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002459
2460 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002461 assert(lhptee->isFunctionType());
2462 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002463 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002464
2465 // Check for ObjC interfaces
2466 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2467 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2468 if (LHSIface && RHSIface &&
2469 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2470 return ConvTy;
2471
2472 // ID acts sort of like void* for ObjC interfaces
Steve Naroff389bf462009-02-12 17:52:19 +00002473 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman3d815e72008-08-22 00:56:42 +00002474 return ConvTy;
Steve Naroff389bf462009-02-12 17:52:19 +00002475 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman3d815e72008-08-22 00:56:42 +00002476 return ConvTy;
2477
Reid Spencer5f016e22007-07-11 17:01:13 +00002478 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2479 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002480 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2481 rhptee.getUnqualifiedType()))
2482 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002483 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002484}
2485
Steve Naroff1c7d0672008-09-04 15:10:53 +00002486/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2487/// block pointer types are compatible or whether a block and normal pointer
2488/// are compatible. It is more restrict than comparing two function pointer
2489// types.
2490Sema::AssignConvertType
2491Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2492 QualType rhsType) {
2493 QualType lhptee, rhptee;
2494
2495 // get the "pointed to" type (ignoring qualifiers at the top level)
2496 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2497 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2498
2499 // make sure we operate on the canonical type
2500 lhptee = Context.getCanonicalType(lhptee);
2501 rhptee = Context.getCanonicalType(rhptee);
2502
2503 AssignConvertType ConvTy = Compatible;
2504
2505 // For blocks we enforce that qualifiers are identical.
2506 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2507 ConvTy = CompatiblePointerDiscardsQualifiers;
2508
2509 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2510 return IncompatibleBlockPointer;
2511 return ConvTy;
2512}
2513
Reid Spencer5f016e22007-07-11 17:01:13 +00002514/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2515/// has code to accommodate several GCC extensions when type checking
2516/// pointers. Here are some objectionable examples that GCC considers warnings:
2517///
2518/// int a, *pint;
2519/// short *pshort;
2520/// struct foo *pfoo;
2521///
2522/// pint = pshort; // warning: assignment from incompatible pointer type
2523/// a = pint; // warning: assignment makes integer from pointer without a cast
2524/// pint = a; // warning: assignment makes pointer from integer without a cast
2525/// pint = pfoo; // warning: assignment from incompatible pointer type
2526///
2527/// As a result, the code for dealing with pointers is more complex than the
2528/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002529///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002530Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002531Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002532 // Get canonical types. We're not formatting these types, just comparing
2533 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002534 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2535 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002536
2537 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002538 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002539
Douglas Gregor9d293df2008-10-28 00:22:11 +00002540 // If the left-hand side is a reference type, then we are in a
2541 // (rare!) case where we've allowed the use of references in C,
2542 // e.g., as a parameter type in a built-in function. In this case,
2543 // just make sure that the type referenced is compatible with the
2544 // right-hand side type. The caller is responsible for adjusting
2545 // lhsType so that the resulting expression does not have reference
2546 // type.
2547 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2548 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002549 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002550 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002551 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002552
Chris Lattnereca7be62008-04-07 05:30:13 +00002553 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2554 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002555 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002556 // Relax integer conversions like we do for pointers below.
2557 if (rhsType->isIntegerType())
2558 return IntToPointer;
2559 if (lhsType->isIntegerType())
2560 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002561 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002562 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002563
Nate Begemanbe2341d2008-07-14 18:02:46 +00002564 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002565 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002566 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2567 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002568 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002569
Nate Begemanbe2341d2008-07-14 18:02:46 +00002570 // If we are allowing lax vector conversions, and LHS and RHS are both
2571 // vectors, the total size only needs to be the same. This is a bitcast;
2572 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002573 if (getLangOptions().LaxVectorConversions &&
2574 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002575 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002576 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002577 }
2578 return Incompatible;
2579 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002580
Chris Lattnere8b3e962008-01-04 23:32:24 +00002581 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002583
Chris Lattner78eca282008-04-07 06:49:41 +00002584 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002586 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002587
Chris Lattner78eca282008-04-07 06:49:41 +00002588 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002590
Steve Naroffb4406862008-09-29 18:10:17 +00002591 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002592 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002593 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002594
2595 // Treat block pointers as objects.
2596 if (getLangOptions().ObjC1 &&
2597 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2598 return Compatible;
2599 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002600 return Incompatible;
2601 }
2602
2603 if (isa<BlockPointerType>(lhsType)) {
2604 if (rhsType->isIntegerType())
2605 return IntToPointer;
2606
Steve Naroffb4406862008-09-29 18:10:17 +00002607 // Treat block pointers as objects.
2608 if (getLangOptions().ObjC1 &&
2609 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2610 return Compatible;
2611
Steve Naroff1c7d0672008-09-04 15:10:53 +00002612 if (rhsType->isBlockPointerType())
2613 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2614
2615 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2616 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002617 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002618 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002619 return Incompatible;
2620 }
2621
Chris Lattner78eca282008-04-07 06:49:41 +00002622 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002623 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002624 if (lhsType == Context.BoolTy)
2625 return Compatible;
2626
2627 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002628 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629
Chris Lattner78eca282008-04-07 06:49:41 +00002630 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002632
2633 if (isa<BlockPointerType>(lhsType) &&
2634 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002635 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002636 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002637 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002638
Chris Lattnerfc144e22008-01-04 23:18:45 +00002639 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002640 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 }
2643 return Incompatible;
2644}
2645
Chris Lattner5cf216b2008-01-04 18:04:52 +00002646Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002647Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002648 if (getLangOptions().CPlusPlus) {
2649 if (!lhsType->isRecordType()) {
2650 // C++ 5.17p3: If the left operand is not of class type, the
2651 // expression is implicitly converted (C++ 4) to the
2652 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002653 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2654 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002655 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002656 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002657 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002658 }
2659
2660 // FIXME: Currently, we fall through and treat C++ classes like C
2661 // structures.
2662 }
2663
Steve Naroff529a4ad2007-11-27 17:58:44 +00002664 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2665 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002666 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2667 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002668 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002669 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002670 return Compatible;
2671 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002672
2673 // We don't allow conversion of non-null-pointer constants to integers.
2674 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2675 return IntToBlockPointer;
2676
Chris Lattner943140e2007-10-16 02:55:40 +00002677 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002678 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002679 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002680 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002681 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002682 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002683 if (!lhsType->isReferenceType())
2684 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002685
Chris Lattner5cf216b2008-01-04 18:04:52 +00002686 Sema::AssignConvertType result =
2687 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002688
2689 // C99 6.5.16.1p2: The value of the right operand is converted to the
2690 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002691 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2692 // so that we can use references in built-in functions even in C.
2693 // The getNonReferenceType() call makes sure that the resulting expression
2694 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002695 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002696 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002697 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002698}
2699
Chris Lattner5cf216b2008-01-04 18:04:52 +00002700Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002701Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2702 return CheckAssignmentConstraints(lhsType, rhsType);
2703}
2704
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002705QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002706 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002707 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002708 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002709 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002710}
2711
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002712inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002713 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002714 // For conversion purposes, we ignore any qualifiers.
2715 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002716 QualType lhsType =
2717 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2718 QualType rhsType =
2719 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002720
Nate Begemanbe2341d2008-07-14 18:02:46 +00002721 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002722 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002724
Nate Begemanbe2341d2008-07-14 18:02:46 +00002725 // Handle the case of a vector & extvector type of the same size and element
2726 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002727 if (getLangOptions().LaxVectorConversions) {
2728 // FIXME: Should we warn here?
2729 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002730 if (const VectorType *RV = rhsType->getAsVectorType())
2731 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002732 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002733 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002734 }
2735 }
2736 }
2737
Nate Begemanbe2341d2008-07-14 18:02:46 +00002738 // If the lhs is an extended vector and the rhs is a scalar of the same type
2739 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002740 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002741 QualType eltType = V->getElementType();
2742
2743 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2744 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2745 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002746 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002747 return lhsType;
2748 }
2749 }
2750
Nate Begemanbe2341d2008-07-14 18:02:46 +00002751 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002752 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002753 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002754 QualType eltType = V->getElementType();
2755
2756 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2757 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2758 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002759 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002760 return rhsType;
2761 }
2762 }
2763
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002765 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002766 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002767 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00002769}
2770
Reid Spencer5f016e22007-07-11 17:01:13 +00002771inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002772 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002773{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002774 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002775 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002776
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002777 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002778
Steve Naroffa4332e22007-07-17 00:58:39 +00002779 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002780 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002781 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002782}
2783
2784inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002785 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002786{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002787 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2788 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2789 return CheckVectorOperands(Loc, lex, rex);
2790 return InvalidOperands(Loc, lex, rex);
2791 }
Steve Naroff90045e82007-07-13 23:32:42 +00002792
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002793 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002794
Steve Naroffa4332e22007-07-17 00:58:39 +00002795 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002796 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002797 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002798}
2799
2800inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002801 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002802{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002803 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002804 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002805
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002806 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002807
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002809 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002810 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002811
Eli Friedmand72d16e2008-05-18 18:08:51 +00002812 // Put any potential pointer into PExp
2813 Expr* PExp = lex, *IExp = rex;
2814 if (IExp->getType()->isPointerType())
2815 std::swap(PExp, IExp);
2816
2817 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2818 if (IExp->getType()->isIntegerType()) {
2819 // Check for arithmetic on pointers to incomplete types
2820 if (!PTy->getPointeeType()->isObjectType()) {
2821 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002822 if (getLangOptions().CPlusPlus) {
2823 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2824 << lex->getSourceRange() << rex->getSourceRange();
2825 return QualType();
2826 }
2827
2828 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002829 Diag(Loc, diag::ext_gnu_void_ptr)
2830 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002831 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002832 if (getLangOptions().CPlusPlus) {
2833 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2834 << lex->getType() << lex->getSourceRange();
2835 return QualType();
2836 }
2837
2838 // GNU extension: arithmetic on pointer to function
2839 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00002840 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002841 } else {
2842 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2843 diag::err_typecheck_arithmetic_incomplete_type,
2844 lex->getSourceRange(), SourceRange(),
2845 lex->getType());
2846 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002847 }
2848 }
2849 return PExp->getType();
2850 }
2851 }
2852
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002853 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002854}
2855
Chris Lattnereca7be62008-04-07 05:30:13 +00002856// C99 6.5.6
2857QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002858 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002859 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002860 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002861
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002862 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002863
Chris Lattner6e4ab612007-12-09 21:53:25 +00002864 // Enforce type constraints: C99 6.5.6p3.
2865
2866 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002867 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002868 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002869
2870 // Either ptr - int or ptr - ptr.
2871 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002872 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002873
Chris Lattner6e4ab612007-12-09 21:53:25 +00002874 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002875 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002876 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002877 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002878 Diag(Loc, diag::ext_gnu_void_ptr)
2879 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00002880 } else if (lpointee->isFunctionType()) {
2881 if (getLangOptions().CPlusPlus) {
2882 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2883 << lex->getType() << lex->getSourceRange();
2884 return QualType();
2885 }
2886
2887 // GNU extension: arithmetic on pointer to function
2888 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2889 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002890 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002891 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002892 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002893 return QualType();
2894 }
2895 }
2896
2897 // The result type of a pointer-int computation is the pointer type.
2898 if (rex->getType()->isIntegerType())
2899 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002900
Chris Lattner6e4ab612007-12-09 21:53:25 +00002901 // Handle pointer-pointer subtractions.
2902 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002903 QualType rpointee = RHSPTy->getPointeeType();
2904
Chris Lattner6e4ab612007-12-09 21:53:25 +00002905 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002906 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002907 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002908 if (rpointee->isVoidType()) {
2909 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002910 Diag(Loc, diag::ext_gnu_void_ptr)
2911 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00002912 } else if (rpointee->isFunctionType()) {
2913 if (getLangOptions().CPlusPlus) {
2914 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2915 << rex->getType() << rex->getSourceRange();
2916 return QualType();
2917 }
2918
2919 // GNU extension: arithmetic on pointer to function
2920 if (!lpointee->isFunctionType())
2921 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2922 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002923 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002924 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002925 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002926 return QualType();
2927 }
2928 }
2929
2930 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002931 if (!Context.typesAreCompatible(
2932 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2933 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002934 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002935 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002936 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002937 return QualType();
2938 }
2939
2940 return Context.getPointerDiffType();
2941 }
2942 }
2943
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002944 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002945}
2946
Chris Lattnereca7be62008-04-07 05:30:13 +00002947// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002948QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002949 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002950 // C99 6.5.7p2: Each of the operands shall have integer type.
2951 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002952 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002953
Chris Lattnerca5eede2007-12-12 05:47:28 +00002954 // Shifts don't perform usual arithmetic conversions, they just do integer
2955 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002956 if (!isCompAssign)
2957 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002958 UsualUnaryConversions(rex);
2959
2960 // "The type of the result is that of the promoted left operand."
2961 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002962}
2963
Chris Lattnereca7be62008-04-07 05:30:13 +00002964// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002965QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002966 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002967 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002968 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002969
Chris Lattnera5937dd2007-08-26 01:18:55 +00002970 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002971 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2972 UsualArithmeticConversions(lex, rex);
2973 else {
2974 UsualUnaryConversions(lex);
2975 UsualUnaryConversions(rex);
2976 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002977 QualType lType = lex->getType();
2978 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002979
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002980 // For non-floating point types, check for self-comparisons of the form
2981 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2982 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002983 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002984 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2985 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002986 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002987 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002988 }
2989
Douglas Gregor447b69e2008-11-19 03:25:36 +00002990 // The result of comparisons is 'bool' in C++, 'int' in C.
2991 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2992
Chris Lattnera5937dd2007-08-26 01:18:55 +00002993 if (isRelational) {
2994 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002995 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002996 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002997 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002998 if (lType->isFloatingType()) {
2999 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003000 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00003001 }
3002
Chris Lattnera5937dd2007-08-26 01:18:55 +00003003 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003004 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003005 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003006
Chris Lattnerd28f8152007-08-26 01:10:14 +00003007 bool LHSIsNull = lex->isNullPointerConstant(Context);
3008 bool RHSIsNull = rex->isNullPointerConstant(Context);
3009
Chris Lattnera5937dd2007-08-26 01:18:55 +00003010 // All of the following pointer related warnings are GCC extensions, except
3011 // when handling null pointer constants. One day, we can consider making them
3012 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00003013 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003014 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003015 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00003016 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003017 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00003018
Steve Naroff66296cb2007-11-13 14:57:38 +00003019 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003020 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3021 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00003022 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff389bf462009-02-12 17:52:19 +00003023 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003024 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003025 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003026 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00003027 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003028 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003029 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003030 // Handle block pointer types.
3031 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3032 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3033 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3034
3035 if (!LHSIsNull && !RHSIsNull &&
3036 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003037 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003038 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00003039 }
3040 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003041 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003042 }
Steve Naroff59f53942008-09-28 01:11:11 +00003043 // Allow block pointers to be compared with null pointer constants.
3044 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3045 (lType->isPointerType() && rType->isBlockPointerType())) {
3046 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003047 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003048 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00003049 }
3050 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003051 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00003052 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003053
Steve Naroff20373222008-06-03 14:04:54 +00003054 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00003055 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00003056 const PointerType *LPT = lType->getAsPointerType();
3057 const PointerType *RPT = rType->getAsPointerType();
3058 bool LPtrToVoid = LPT ?
3059 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3060 bool RPtrToVoid = RPT ?
3061 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3062
3063 if (!LPtrToVoid && !RPtrToVoid &&
3064 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003065 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003066 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00003067 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003068 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00003069 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003070 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003071 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00003072 }
Steve Naroff20373222008-06-03 14:04:54 +00003073 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3074 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003075 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003076 } else {
3077 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003078 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003079 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003080 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003081 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003082 }
Steve Naroff20373222008-06-03 14:04:54 +00003083 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00003084 }
Steve Naroff20373222008-06-03 14:04:54 +00003085 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3086 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003087 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003088 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003089 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003090 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003091 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003092 }
Steve Naroff20373222008-06-03 14:04:54 +00003093 if (lType->isIntegerType() &&
3094 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003095 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003096 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003097 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003098 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003099 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 }
Steve Naroff39218df2008-09-04 16:56:14 +00003101 // Handle block pointers.
3102 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3103 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003104 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003105 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003106 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003107 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003108 }
3109 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3110 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003111 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003112 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003113 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003114 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003115 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003116 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003117}
3118
Nate Begemanbe2341d2008-07-14 18:02:46 +00003119/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3120/// operates on extended vector types. Instead of producing an IntTy result,
3121/// like a scalar comparison, a vector comparison produces a vector of integer
3122/// types.
3123QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003124 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003125 bool isRelational) {
3126 // Check to make sure we're operating on vectors of the same type and width,
3127 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003128 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003129 if (vType.isNull())
3130 return vType;
3131
3132 QualType lType = lex->getType();
3133 QualType rType = rex->getType();
3134
3135 // For non-floating point types, check for self-comparisons of the form
3136 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3137 // often indicate logic errors in the program.
3138 if (!lType->isFloatingType()) {
3139 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3140 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3141 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003142 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003143 }
3144
3145 // Check for comparisons of floating point operands using != and ==.
3146 if (!isRelational && lType->isFloatingType()) {
3147 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003148 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003149 }
3150
3151 // Return the type for the comparison, which is the same as vector type for
3152 // integer vectors, or an integer type of identical size and number of
3153 // elements for floating point vectors.
3154 if (lType->isIntegerType())
3155 return lType;
3156
3157 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003158 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003159 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003160 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003161 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3162 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3163
3164 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3165 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003166 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3167}
3168
Reid Spencer5f016e22007-07-11 17:01:13 +00003169inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003170 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003171{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003172 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003173 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003174
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003175 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00003176
Steve Naroffa4332e22007-07-17 00:58:39 +00003177 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003178 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003179 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003180}
3181
3182inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003183 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003184{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003185 UsualUnaryConversions(lex);
3186 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003187
Eli Friedman5773a6c2008-05-13 20:16:47 +00003188 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003190 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003191}
3192
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003193/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3194/// is a read-only property; return true if so. A readonly property expression
3195/// depends on various declarations and thus must be treated specially.
3196///
3197static bool IsReadonlyProperty(Expr *E, Sema &S)
3198{
3199 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3200 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3201 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3202 QualType BaseType = PropExpr->getBase()->getType();
3203 if (const PointerType *PTy = BaseType->getAsPointerType())
3204 if (const ObjCInterfaceType *IFTy =
3205 PTy->getPointeeType()->getAsObjCInterfaceType())
3206 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3207 if (S.isPropertyReadonly(PDecl, IFace))
3208 return true;
3209 }
3210 }
3211 return false;
3212}
3213
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003214/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3215/// emit an error and return true. If so, return false.
3216static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003217 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3218 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3219 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003220 if (IsLV == Expr::MLV_Valid)
3221 return false;
3222
3223 unsigned Diag = 0;
3224 bool NeedType = false;
3225 switch (IsLV) { // C99 6.5.16p2
3226 default: assert(0 && "Unknown result from isModifiableLvalue!");
3227 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003228 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003229 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3230 NeedType = true;
3231 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003232 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003233 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3234 NeedType = true;
3235 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003236 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003237 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3238 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003239 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003240 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3241 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003242 case Expr::MLV_IncompleteType:
3243 case Expr::MLV_IncompleteVoidType:
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003244 return S.DiagnoseIncompleteType(Loc, E->getType(),
3245 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3246 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003247 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003248 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3249 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003250 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003251 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3252 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003253 case Expr::MLV_ReadonlyProperty:
3254 Diag = diag::error_readonly_property_assignment;
3255 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003256 case Expr::MLV_NoSetterProperty:
3257 Diag = diag::error_nosetter_property_assignment;
3258 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003259 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003260
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003261 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003262 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003263 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003264 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003265 return true;
3266}
3267
3268
3269
3270// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003271QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3272 SourceLocation Loc,
3273 QualType CompoundType) {
3274 // Verify that LHS is a modifiable lvalue, and emit error if not.
3275 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003276 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003277
3278 QualType LHSType = LHS->getType();
3279 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003280
Chris Lattner5cf216b2008-01-04 18:04:52 +00003281 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003282 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003283 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003284 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003285 // Special case of NSObject attributes on c-style pointer types.
3286 if (ConvTy == IncompatiblePointer &&
3287 ((Context.isObjCNSObjectType(LHSType) &&
3288 Context.isObjCObjectPointerType(RHSType)) ||
3289 (Context.isObjCNSObjectType(RHSType) &&
3290 Context.isObjCObjectPointerType(LHSType))))
3291 ConvTy = Compatible;
3292
Chris Lattner2c156472008-08-21 18:04:13 +00003293 // If the RHS is a unary plus or minus, check to see if they = and + are
3294 // right next to each other. If so, the user may have typo'd "x =+ 4"
3295 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003296 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003297 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3298 RHSCheck = ICE->getSubExpr();
3299 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3300 if ((UO->getOpcode() == UnaryOperator::Plus ||
3301 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003302 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003303 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003304 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003305 Diag(Loc, diag::warn_not_compound_assign)
3306 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3307 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003308 }
3309 } else {
3310 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003311 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003312 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003313
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003314 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3315 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003316 return QualType();
3317
Reid Spencer5f016e22007-07-11 17:01:13 +00003318 // C99 6.5.16p3: The type of an assignment expression is the type of the
3319 // left operand unless the left operand has qualified type, in which case
3320 // it is the unqualified version of the type of the left operand.
3321 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3322 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003323 // C++ 5.17p1: the type of the assignment expression is that of its left
3324 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003325 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003326}
3327
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003328// C99 6.5.17
3329QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3330 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003331
3332 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003333 DefaultFunctionArrayConversion(RHS);
3334 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003335}
3336
Steve Naroff49b45262007-07-13 16:58:59 +00003337/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3338/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003339QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3340 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003341 QualType ResType = Op->getType();
3342 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003343
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003344 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3345 // Decrement of bool is not allowed.
3346 if (!isInc) {
3347 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3348 return QualType();
3349 }
3350 // Increment of bool sets it to true, but is deprecated.
3351 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3352 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003353 // OK!
3354 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3355 // C99 6.5.2.4p2, 6.5.6p2
3356 if (PT->getPointeeType()->isObjectType()) {
3357 // Pointer to object is ok!
3358 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003359 if (getLangOptions().CPlusPlus) {
3360 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3361 << Op->getSourceRange();
3362 return QualType();
3363 }
3364
3365 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003366 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003367 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003368 if (getLangOptions().CPlusPlus) {
3369 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3370 << Op->getType() << Op->getSourceRange();
3371 return QualType();
3372 }
3373
3374 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003375 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003376 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003377 } else {
3378 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3379 diag::err_typecheck_arithmetic_incomplete_type,
3380 Op->getSourceRange(), SourceRange(),
3381 ResType);
3382 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003383 }
Chris Lattner3528d352008-11-21 07:05:48 +00003384 } else if (ResType->isComplexType()) {
3385 // C99 does not support ++/-- on complex types, we allow as an extension.
3386 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003387 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003388 } else {
3389 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003390 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003391 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003392 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003393 // At this point, we know we have a real, complex or pointer type.
3394 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003395 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003396 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003397 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003398}
3399
Anders Carlsson369dee42008-02-01 07:15:58 +00003400/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003401/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003402/// where the declaration is needed for type checking. We only need to
3403/// handle cases when the expression references a function designator
3404/// or is an lvalue. Here are some examples:
3405/// - &(x) => x
3406/// - &*****f => f for f a function designator.
3407/// - &s.xx => s
3408/// - &s.zz[1].yy -> s, if zz is an array
3409/// - *(x + 1) -> x, if x is an array
3410/// - &"123"[2] -> 0
3411/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003412static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003413 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003414 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003415 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003416 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003418 // Fields cannot be declared with a 'register' storage class.
3419 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003420 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003421 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003422 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003423 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003424 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003425
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003426 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003427 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003428 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003429 return 0;
3430 else
3431 return VD;
3432 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003433 case Stmt::UnaryOperatorClass: {
3434 UnaryOperator *UO = cast<UnaryOperator>(E);
3435
3436 switch(UO->getOpcode()) {
3437 case UnaryOperator::Deref: {
3438 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003439 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3440 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3441 if (!VD || VD->getType()->isPointerType())
3442 return 0;
3443 return VD;
3444 }
3445 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003446 }
3447 case UnaryOperator::Real:
3448 case UnaryOperator::Imag:
3449 case UnaryOperator::Extension:
3450 return getPrimaryDecl(UO->getSubExpr());
3451 default:
3452 return 0;
3453 }
3454 }
3455 case Stmt::BinaryOperatorClass: {
3456 BinaryOperator *BO = cast<BinaryOperator>(E);
3457
3458 // Handle cases involving pointer arithmetic. The result of an
3459 // Assign or AddAssign is not an lvalue so they can be ignored.
3460
3461 // (x + n) or (n + x) => x
3462 if (BO->getOpcode() == BinaryOperator::Add) {
3463 if (BO->getLHS()->getType()->isPointerType()) {
3464 return getPrimaryDecl(BO->getLHS());
3465 } else if (BO->getRHS()->getType()->isPointerType()) {
3466 return getPrimaryDecl(BO->getRHS());
3467 }
3468 }
3469
3470 return 0;
3471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003472 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003473 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003474 case Stmt::ImplicitCastExprClass:
3475 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003476 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003477 default:
3478 return 0;
3479 }
3480}
3481
3482/// CheckAddressOfOperand - The operand of & must be either a function
3483/// designator or an lvalue designating an object. If it is an lvalue, the
3484/// object cannot be declared with storage class register or be a bit field.
3485/// Note: The usual conversions are *not* applied to the operand of the &
3486/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003487/// In C++, the operand might be an overloaded function name, in which case
3488/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003489QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003490 if (op->isTypeDependent())
3491 return Context.DependentTy;
3492
Steve Naroff08f19672008-01-13 17:10:08 +00003493 if (getLangOptions().C99) {
3494 // Implement C99-only parts of addressof rules.
3495 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3496 if (uOp->getOpcode() == UnaryOperator::Deref)
3497 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3498 // (assuming the deref expression is valid).
3499 return uOp->getSubExpr()->getType();
3500 }
3501 // Technically, there should be a check for array subscript
3502 // expressions here, but the result of one is always an lvalue anyway.
3503 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003504 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003505 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003506
Reid Spencer5f016e22007-07-11 17:01:13 +00003507 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003508 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3509 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003510 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3511 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003512 return QualType();
3513 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003514 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003515 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3516 if (Field->isBitField()) {
3517 Diag(OpLoc, diag::err_typecheck_address_of)
3518 << "bit-field" << op->getSourceRange();
3519 return QualType();
3520 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003521 }
3522 // Check for Apple extension for accessing vector components.
Nate Begemanb104b1f2009-02-15 22:45:20 +00003523 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3524 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003525 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00003526 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003527 return QualType();
3528 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003529 // We have an lvalue with a decl. Make sure the decl is not declared
3530 // with the register storage-class specifier.
3531 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3532 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003533 Diag(OpLoc, diag::err_typecheck_address_of)
3534 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003535 return QualType();
3536 }
Douglas Gregor29882052008-12-10 21:26:49 +00003537 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003538 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003539 } else if (isa<FieldDecl>(dcl)) {
3540 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00003541 // Could be a pointer to member, though, if there is an explicit
3542 // scope qualifier for the class.
3543 if (isa<QualifiedDeclRefExpr>(op)) {
3544 DeclContext *Ctx = dcl->getDeclContext();
3545 if (Ctx && Ctx->isRecord())
3546 return Context.getMemberPointerType(op->getType(),
3547 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3548 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003549 } else if (isa<FunctionDecl>(dcl)) {
3550 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00003551 // As above.
3552 if (isa<QualifiedDeclRefExpr>(op)) {
3553 DeclContext *Ctx = dcl->getDeclContext();
3554 if (Ctx && Ctx->isRecord())
3555 return Context.getMemberPointerType(op->getType(),
3556 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3557 }
Douglas Gregor29882052008-12-10 21:26:49 +00003558 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003559 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003560 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003561 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00003562
Reid Spencer5f016e22007-07-11 17:01:13 +00003563 // If the operand has type "type", the result has type "pointer to type".
3564 return Context.getPointerType(op->getType());
3565}
3566
Chris Lattner22caddc2008-11-23 09:13:29 +00003567QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3568 UsualUnaryConversions(Op);
3569 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003570
Chris Lattner22caddc2008-11-23 09:13:29 +00003571 // Note that per both C89 and C99, this is always legal, even if ptype is an
3572 // incomplete type or void. It would be possible to warn about dereferencing
3573 // a void pointer, but it's completely well-defined, and such a warning is
3574 // unlikely to catch any mistakes.
3575 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003576 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003577
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003578 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003579 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003580 return QualType();
3581}
3582
3583static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3584 tok::TokenKind Kind) {
3585 BinaryOperator::Opcode Opc;
3586 switch (Kind) {
3587 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00003588 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3589 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003590 case tok::star: Opc = BinaryOperator::Mul; break;
3591 case tok::slash: Opc = BinaryOperator::Div; break;
3592 case tok::percent: Opc = BinaryOperator::Rem; break;
3593 case tok::plus: Opc = BinaryOperator::Add; break;
3594 case tok::minus: Opc = BinaryOperator::Sub; break;
3595 case tok::lessless: Opc = BinaryOperator::Shl; break;
3596 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3597 case tok::lessequal: Opc = BinaryOperator::LE; break;
3598 case tok::less: Opc = BinaryOperator::LT; break;
3599 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3600 case tok::greater: Opc = BinaryOperator::GT; break;
3601 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3602 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3603 case tok::amp: Opc = BinaryOperator::And; break;
3604 case tok::caret: Opc = BinaryOperator::Xor; break;
3605 case tok::pipe: Opc = BinaryOperator::Or; break;
3606 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3607 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3608 case tok::equal: Opc = BinaryOperator::Assign; break;
3609 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3610 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3611 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3612 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3613 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3614 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3615 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3616 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3617 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3618 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3619 case tok::comma: Opc = BinaryOperator::Comma; break;
3620 }
3621 return Opc;
3622}
3623
3624static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3625 tok::TokenKind Kind) {
3626 UnaryOperator::Opcode Opc;
3627 switch (Kind) {
3628 default: assert(0 && "Unknown unary op!");
3629 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3630 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3631 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3632 case tok::star: Opc = UnaryOperator::Deref; break;
3633 case tok::plus: Opc = UnaryOperator::Plus; break;
3634 case tok::minus: Opc = UnaryOperator::Minus; break;
3635 case tok::tilde: Opc = UnaryOperator::Not; break;
3636 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003637 case tok::kw___real: Opc = UnaryOperator::Real; break;
3638 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3639 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3640 }
3641 return Opc;
3642}
3643
Douglas Gregoreaebc752008-11-06 23:29:22 +00003644/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3645/// operator @p Opc at location @c TokLoc. This routine only supports
3646/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003647Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3648 unsigned Op,
3649 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003650 QualType ResultTy; // Result type of the binary operator.
3651 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3652 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3653
3654 switch (Opc) {
3655 default:
3656 assert(0 && "Unknown binary expr!");
3657 case BinaryOperator::Assign:
3658 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3659 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003660 case BinaryOperator::PtrMemD:
3661 case BinaryOperator::PtrMemI:
3662 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3663 Opc == BinaryOperator::PtrMemI);
3664 break;
3665 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003666 case BinaryOperator::Div:
3667 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3668 break;
3669 case BinaryOperator::Rem:
3670 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3671 break;
3672 case BinaryOperator::Add:
3673 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3674 break;
3675 case BinaryOperator::Sub:
3676 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3677 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003678 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003679 case BinaryOperator::Shr:
3680 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3681 break;
3682 case BinaryOperator::LE:
3683 case BinaryOperator::LT:
3684 case BinaryOperator::GE:
3685 case BinaryOperator::GT:
3686 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3687 break;
3688 case BinaryOperator::EQ:
3689 case BinaryOperator::NE:
3690 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3691 break;
3692 case BinaryOperator::And:
3693 case BinaryOperator::Xor:
3694 case BinaryOperator::Or:
3695 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3696 break;
3697 case BinaryOperator::LAnd:
3698 case BinaryOperator::LOr:
3699 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3700 break;
3701 case BinaryOperator::MulAssign:
3702 case BinaryOperator::DivAssign:
3703 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3704 if (!CompTy.isNull())
3705 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3706 break;
3707 case BinaryOperator::RemAssign:
3708 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3709 if (!CompTy.isNull())
3710 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3711 break;
3712 case BinaryOperator::AddAssign:
3713 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3714 if (!CompTy.isNull())
3715 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3716 break;
3717 case BinaryOperator::SubAssign:
3718 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3719 if (!CompTy.isNull())
3720 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3721 break;
3722 case BinaryOperator::ShlAssign:
3723 case BinaryOperator::ShrAssign:
3724 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3725 if (!CompTy.isNull())
3726 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3727 break;
3728 case BinaryOperator::AndAssign:
3729 case BinaryOperator::XorAssign:
3730 case BinaryOperator::OrAssign:
3731 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3732 if (!CompTy.isNull())
3733 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3734 break;
3735 case BinaryOperator::Comma:
3736 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3737 break;
3738 }
3739 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003740 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003741 if (CompTy.isNull())
3742 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3743 else
3744 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff9e0b6002009-01-20 21:06:31 +00003745 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00003746}
3747
Reid Spencer5f016e22007-07-11 17:01:13 +00003748// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003749Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3750 tok::TokenKind Kind,
3751 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003752 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003753 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00003754
Steve Narofff69936d2007-09-16 03:34:24 +00003755 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3756 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003757
Douglas Gregor898574e2008-12-05 23:32:09 +00003758 // If either expression is type-dependent, just build the AST.
3759 // FIXME: We'll need to perform some caching of the result of name
3760 // lookup for operator+.
3761 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00003762 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3763 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003764 Context.DependentTy,
3765 Context.DependentTy, TokLoc));
Steve Naroff6ece14c2009-01-21 00:14:39 +00003766 else
Sebastian Redl22460502009-02-07 00:15:38 +00003767 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3768 Context.DependentTy, TokLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00003769 }
3770
Sebastian Redl22460502009-02-07 00:15:38 +00003771 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregoreaebc752008-11-06 23:29:22 +00003772 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3773 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003774 // If this is one of the assignment operators, we only perform
3775 // overload resolution if the left-hand side is a class or
3776 // enumeration type (C++ [expr.ass]p3).
3777 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3778 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3779 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3780 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003781
Douglas Gregoreaebc752008-11-06 23:29:22 +00003782 // Determine which overloaded operator we're dealing with.
3783 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl22460502009-02-07 00:15:38 +00003784 // Overloading .* is not possible.
3785 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregoreaebc752008-11-06 23:29:22 +00003786 OO_Star, OO_Slash, OO_Percent,
3787 OO_Plus, OO_Minus,
3788 OO_LessLess, OO_GreaterGreater,
3789 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3790 OO_EqualEqual, OO_ExclaimEqual,
3791 OO_Amp,
3792 OO_Caret,
3793 OO_Pipe,
3794 OO_AmpAmp,
3795 OO_PipePipe,
3796 OO_Equal, OO_StarEqual,
3797 OO_SlashEqual, OO_PercentEqual,
3798 OO_PlusEqual, OO_MinusEqual,
3799 OO_LessLessEqual, OO_GreaterGreaterEqual,
3800 OO_AmpEqual, OO_CaretEqual,
3801 OO_PipeEqual,
3802 OO_Comma
3803 };
3804 OverloadedOperatorKind OverOp = OverOps[Opc];
3805
Douglas Gregor96176b32008-11-18 23:14:02 +00003806 // Add the appropriate overloaded operators (C++ [over.match.oper])
3807 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003808 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003809 Expr *Args[2] = { lhs, rhs };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003810 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3811 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003812
3813 // Perform overload resolution.
3814 OverloadCandidateSet::iterator Best;
3815 switch (BestViableFunction(CandidateSet, Best)) {
3816 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003817 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003818 FunctionDecl *FnDecl = Best->Function;
3819
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003820 if (FnDecl) {
3821 // We matched an overloaded operator. Build a call to that
3822 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003823
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003824 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003825 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3826 if (PerformObjectArgumentInitialization(lhs, Method) ||
3827 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3828 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003829 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003830 } else {
3831 // Convert the arguments.
3832 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3833 "passing") ||
3834 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3835 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003836 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003837 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003838
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003839 // Determine the result type
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003840 QualType ResultTy
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003841 = FnDecl->getType()->getAsFunctionType()->getResultType();
3842 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003843
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003844 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003845 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3846 SourceLocation());
Douglas Gregorb4609802008-11-14 16:09:21 +00003847 UsualUnaryConversions(FnExpr);
3848
Ted Kremenek668bf912009-02-09 20:51:47 +00003849 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003850 ResultTy, TokLoc));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003851 } else {
3852 // We matched a built-in operator. Convert the arguments, then
3853 // break out so that we will build the appropriate built-in
3854 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003855 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3856 Best->Conversions[0], "passing") ||
3857 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3858 Best->Conversions[1], "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003859 return ExprError();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003860
3861 break;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003862 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003863 }
3864
3865 case OR_No_Viable_Function:
3866 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003867 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003868 break;
3869
3870 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003871 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3872 << BinaryOperator::getOpcodeStr(Opc)
3873 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003874 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003875 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003876 }
3877
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003878 // Either we found no viable overloaded operator or we matched a
3879 // built-in operator. In either case, fall through to trying to
3880 // build a built-in operation.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003881 }
3882
Douglas Gregoreaebc752008-11-06 23:29:22 +00003883 // Build a built-in binary operation.
3884 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003885}
3886
3887// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003888Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3889 tok::TokenKind Op, ExprArg input) {
3890 // FIXME: Input is modified later, but smart pointer not reassigned.
3891 Expr *Input = (Expr*)input.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00003892 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003893
3894 if (getLangOptions().CPlusPlus &&
3895 (Input->getType()->isRecordType()
3896 || Input->getType()->isEnumeralType())) {
3897 // Determine which overloaded operator we're dealing with.
3898 static const OverloadedOperatorKind OverOps[] = {
3899 OO_None, OO_None,
3900 OO_PlusPlus, OO_MinusMinus,
3901 OO_Amp, OO_Star,
3902 OO_Plus, OO_Minus,
3903 OO_Tilde, OO_Exclaim,
3904 OO_None, OO_None,
3905 OO_None,
3906 OO_None
3907 };
3908 OverloadedOperatorKind OverOp = OverOps[Opc];
3909
3910 // Add the appropriate overloaded operators (C++ [over.match.oper])
3911 // to the candidate set.
3912 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003913 if (OverOp != OO_None &&
3914 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3915 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003916
3917 // Perform overload resolution.
3918 OverloadCandidateSet::iterator Best;
3919 switch (BestViableFunction(CandidateSet, Best)) {
3920 case OR_Success: {
3921 // We found a built-in operator or an overloaded operator.
3922 FunctionDecl *FnDecl = Best->Function;
3923
3924 if (FnDecl) {
3925 // We matched an overloaded operator. Build a call to that
3926 // operator.
3927
3928 // Convert the arguments.
3929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3930 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003931 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003932 } else {
3933 // Convert the arguments.
3934 if (PerformCopyInitialization(Input,
3935 FnDecl->getParamDecl(0)->getType(),
3936 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003937 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003938 }
3939
3940 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00003941 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00003942 = FnDecl->getType()->getAsFunctionType()->getResultType();
3943 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003944
Douglas Gregor74253732008-11-19 15:42:04 +00003945 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003946 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3947 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00003948 UsualUnaryConversions(FnExpr);
3949
Sebastian Redl0eb23302009-01-19 00:08:26 +00003950 input.release();
Ted Kremenek668bf912009-02-09 20:51:47 +00003951 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003952 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00003953 } else {
3954 // We matched a built-in operator. Convert the arguments, then
3955 // break out so that we will build the appropriate built-in
3956 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003957 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3958 Best->Conversions[0], "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003959 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003960
3961 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00003962 }
Douglas Gregor74253732008-11-19 15:42:04 +00003963 }
3964
3965 case OR_No_Viable_Function:
3966 // No viable function; fall through to handling this as a
3967 // built-in operator, which will produce an error message for us.
3968 break;
3969
3970 case OR_Ambiguous:
3971 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3972 << UnaryOperator::getOpcodeStr(Opc)
3973 << Input->getSourceRange();
3974 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003975 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003976 }
3977
3978 // Either we found no viable overloaded operator or we matched a
3979 // built-in operator. In either case, fall through to trying to
Sebastian Redl0eb23302009-01-19 00:08:26 +00003980 // build a built-in operation.
Douglas Gregor74253732008-11-19 15:42:04 +00003981 }
3982
Reid Spencer5f016e22007-07-11 17:01:13 +00003983 QualType resultType;
3984 switch (Opc) {
3985 default:
3986 assert(0 && "Unimplemented unary expr!");
3987 case UnaryOperator::PreInc:
3988 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003989 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3990 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003991 break;
3992 case UnaryOperator::AddrOf:
3993 resultType = CheckAddressOfOperand(Input, OpLoc);
3994 break;
3995 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003996 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003997 resultType = CheckIndirectionOperand(Input, OpLoc);
3998 break;
3999 case UnaryOperator::Plus:
4000 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004001 UsualUnaryConversions(Input);
4002 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00004003 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4004 break;
4005 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4006 resultType->isEnumeralType())
4007 break;
4008 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4009 Opc == UnaryOperator::Plus &&
4010 resultType->isPointerType())
4011 break;
4012
Sebastian Redl0eb23302009-01-19 00:08:26 +00004013 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4014 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004015 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004016 UsualUnaryConversions(Input);
4017 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00004018 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4019 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4020 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004021 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004022 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00004023 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004024 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4025 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004026 break;
4027 case UnaryOperator::LNot: // logical negation
4028 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004029 DefaultFunctionArrayConversion(Input);
4030 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004031 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00004032 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4033 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004034 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00004035 // In C++, it's bool. C++ 5.3.1p8
4036 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004037 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00004038 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00004039 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00004040 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00004041 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004042 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00004043 resultType = Input->getType();
4044 break;
4045 }
4046 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004047 return ExprError();
4048 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004049 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004050}
4051
Steve Naroff1b273c42007-09-16 14:56:35 +00004052/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4053Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00004054 SourceLocation LabLoc,
4055 IdentifierInfo *LabelII) {
4056 // Look up the record for this label identifier.
4057 LabelStmt *&LabelDecl = LabelMap[LabelII];
4058
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00004059 // If we haven't seen this label yet, create a forward reference. It
4060 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00004061 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00004062 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00004063
4064 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004065 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4066 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00004067}
4068
Steve Naroff1b273c42007-09-16 14:56:35 +00004069Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004070 SourceLocation RPLoc) { // "({..})"
4071 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4072 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4073 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4074
Eli Friedmandca2b732009-01-24 23:09:00 +00004075 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4076 if (isFileScope) {
4077 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4078 }
4079
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004080 // FIXME: there are a variety of strange constraints to enforce here, for
4081 // example, it is not possible to goto into a stmt expression apparently.
4082 // More semantic analysis is needed.
4083
4084 // FIXME: the last statement in the compount stmt has its value used. We
4085 // should not warn about it being unused.
4086
4087 // If there are sub stmts in the compound stmt, take the type of the last one
4088 // as the type of the stmtexpr.
4089 QualType Ty = Context.VoidTy;
4090
Chris Lattner611b2ec2008-07-26 19:51:01 +00004091 if (!Compound->body_empty()) {
4092 Stmt *LastStmt = Compound->body_back();
4093 // If LastStmt is a label, skip down through into the body.
4094 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4095 LastStmt = Label->getSubStmt();
4096
4097 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004098 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004099 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004100
Steve Naroff6ece14c2009-01-21 00:14:39 +00004101 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004102}
Steve Naroffd34e9152007-08-01 22:05:33 +00004103
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004104Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4105 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004106 SourceLocation TypeLoc,
4107 TypeTy *argty,
4108 OffsetOfComponent *CompPtr,
4109 unsigned NumComponents,
4110 SourceLocation RPLoc) {
4111 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4112 assert(!ArgTy.isNull() && "Missing type argument!");
4113
4114 // We must have at least one component that refers to the type, and the first
4115 // one is known to be a field designator. Verify that the ArgTy represents
4116 // a struct/union/class.
4117 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00004118 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004119
4120 // Otherwise, create a compound literal expression as the base, and
4121 // iteratively process the offsetof designators.
Eli Friedman1d242592009-01-26 01:33:06 +00004122 InitListExpr *IList =
Douglas Gregor4c678342009-01-28 21:54:33 +00004123 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004124 IList->setType(ArgTy);
4125 Expr *Res =
4126 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4127
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004128 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4129 // GCC extension, diagnose them.
4130 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004131 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4132 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004133
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004134 for (unsigned i = 0; i != NumComponents; ++i) {
4135 const OffsetOfComponent &OC = CompPtr[i];
4136 if (OC.isBrackets) {
4137 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004138 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004139 if (!AT) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004140 Res->Destroy(Context);
Chris Lattnerd1625842008-11-24 06:25:27 +00004141 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004142 }
4143
Chris Lattner704fe352007-08-30 17:59:59 +00004144 // FIXME: C++: Verify that operator[] isn't overloaded.
4145
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004146 // C99 6.5.2.1p1
4147 Expr *Idx = static_cast<Expr*>(OC.U.E);
4148 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004149 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4150 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004151
Steve Naroff6ece14c2009-01-21 00:14:39 +00004152 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4153 OC.LocEnd);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004154 continue;
4155 }
4156
4157 const RecordType *RC = Res->getType()->getAsRecordType();
4158 if (!RC) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004159 Res->Destroy(Context);
Chris Lattnerd1625842008-11-24 06:25:27 +00004160 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004161 }
4162
4163 // Get the decl corresponding to this.
4164 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004165 FieldDecl *MemberDecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +00004166 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4167 LookupMemberName)
4168 .getAsDecl());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004169 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00004170 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4171 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00004172
4173 // FIXME: C++: Verify that MemberDecl isn't a static field.
4174 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00004175 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4176 // matter here.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004177 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4178 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004179 }
4180
Steve Naroff6ece14c2009-01-21 00:14:39 +00004181 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4182 Context.getSizeType(), BuiltinLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004183}
4184
4185
Steve Naroff1b273c42007-09-16 14:56:35 +00004186Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00004187 TypeTy *arg1, TypeTy *arg2,
4188 SourceLocation RPLoc) {
4189 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4190 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4191
4192 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4193
Steve Naroff6ece14c2009-01-21 00:14:39 +00004194 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4195 argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00004196}
4197
Steve Naroff1b273c42007-09-16 14:56:35 +00004198Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00004199 ExprTy *expr1, ExprTy *expr2,
4200 SourceLocation RPLoc) {
4201 Expr *CondExpr = static_cast<Expr*>(cond);
4202 Expr *LHSExpr = static_cast<Expr*>(expr1);
4203 Expr *RHSExpr = static_cast<Expr*>(expr2);
4204
4205 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4206
4207 // The conditional expression is required to be a constant expression.
4208 llvm::APSInt condEval(32);
4209 SourceLocation ExpLoc;
4210 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004211 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4212 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00004213
4214 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4215 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4216 RHSExpr->getType();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004217 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4218 resType, RPLoc);
Steve Naroffd04fdd52007-08-03 21:21:27 +00004219}
4220
Steve Naroff4eb206b2008-09-03 18:15:37 +00004221//===----------------------------------------------------------------------===//
4222// Clang Extensions.
4223//===----------------------------------------------------------------------===//
4224
4225/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004226void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004227 // Analyze block parameters.
4228 BlockSemaInfo *BSI = new BlockSemaInfo();
4229
4230 // Add BSI to CurBlock.
4231 BSI->PrevBlockInfo = CurBlock;
4232 CurBlock = BSI;
4233
4234 BSI->ReturnType = 0;
4235 BSI->TheScope = BlockScope;
4236
Steve Naroff090276f2008-10-10 01:28:17 +00004237 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004238 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004239}
4240
Mike Stump98eb8a72009-02-04 22:31:32 +00004241void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4242 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4243
4244 if (ParamInfo.getNumTypeObjects() == 0
4245 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4246 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4247
4248 // The type is entirely optional as well, if none, use DependentTy.
4249 if (T.isNull())
4250 T = Context.DependentTy;
4251
4252 // The parameter list is optional, if there was none, assume ().
4253 if (!T->isFunctionType())
4254 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4255
4256 CurBlock->hasPrototype = true;
4257 CurBlock->isVariadic = false;
4258 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4259 .getTypePtr();
4260
4261 if (!RetTy->isDependentType())
4262 CurBlock->ReturnType = RetTy;
4263 return;
4264 }
4265
Steve Naroff4eb206b2008-09-03 18:15:37 +00004266 // Analyze arguments to block.
4267 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4268 "Not a function declarator!");
4269 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump98eb8a72009-02-04 22:31:32 +00004270
Steve Naroff090276f2008-10-10 01:28:17 +00004271 CurBlock->hasPrototype = FTI.hasPrototype;
4272 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004273
4274 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4275 // no arguments, not a function that takes a single void argument.
4276 if (FTI.hasPrototype &&
4277 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4278 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4279 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4280 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004281 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004282 } else if (FTI.hasPrototype) {
4283 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004284 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4285 CurBlock->isVariadic = FTI.isVariadic;
Mike Stump98eb8a72009-02-04 22:31:32 +00004286 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4287
4288 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4289 .getTypePtr();
4290
4291 if (!RetTy->isDependentType())
4292 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004293 }
Steve Naroff090276f2008-10-10 01:28:17 +00004294 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4295
4296 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4297 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4298 // If this has an identifier, add it to the scope stack.
4299 if ((*AI)->getIdentifier())
4300 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004301}
4302
4303/// ActOnBlockError - If there is an error parsing a block, this callback
4304/// is invoked to pop the information about the block from the action impl.
4305void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4306 // Ensure that CurBlock is deleted.
4307 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4308
4309 // Pop off CurBlock, handle nested blocks.
4310 CurBlock = CurBlock->PrevBlockInfo;
4311
4312 // FIXME: Delete the ParmVarDecl objects as well???
4313
4314}
4315
4316/// ActOnBlockStmtExpr - This is called when the body of a block statement
4317/// literal was successfully completed. ^(int x){...}
4318Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4319 Scope *CurScope) {
4320 // Ensure that CurBlock is deleted.
4321 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004322 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff4eb206b2008-09-03 18:15:37 +00004323
Steve Naroff090276f2008-10-10 01:28:17 +00004324 PopDeclContext();
4325
Steve Naroff4eb206b2008-09-03 18:15:37 +00004326 // Pop off CurBlock, handle nested blocks.
4327 CurBlock = CurBlock->PrevBlockInfo;
4328
4329 QualType RetTy = Context.VoidTy;
4330 if (BSI->ReturnType)
4331 RetTy = QualType(BSI->ReturnType, 0);
4332
4333 llvm::SmallVector<QualType, 8> ArgTypes;
4334 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4335 ArgTypes.push_back(BSI->Params[i]->getType());
4336
4337 QualType BlockTy;
4338 if (!BSI->hasPrototype)
4339 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4340 else
4341 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004342 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004343
4344 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00004345
Steve Naroff1c90bfc2008-10-08 18:44:00 +00004346 BSI->TheDecl->setBody(Body.take());
Steve Naroff6ece14c2009-01-21 00:14:39 +00004347 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004348}
4349
Nate Begeman67295d02008-01-30 20:50:20 +00004350/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00004351/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00004352/// The number of arguments has already been validated to match the number of
4353/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004354static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4355 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00004356 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00004357 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00004358 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4359 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00004360
4361 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00004362 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00004363 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004364 return true;
4365}
4366
4367Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4368 SourceLocation *CommaLocs,
4369 SourceLocation BuiltinLoc,
4370 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004371 // __builtin_overload requires at least 2 arguments
4372 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004373 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4374 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004375
Nate Begemane2ce1d92008-01-17 17:46:27 +00004376 // The first argument is required to be a constant expression. It tells us
4377 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004378 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004379 Expr *NParamsExpr = Args[0];
4380 llvm::APSInt constEval(32);
4381 SourceLocation ExpLoc;
4382 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004383 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4384 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004385
4386 // Verify that the number of parameters is > 0
4387 unsigned NumParams = constEval.getZExtValue();
4388 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004389 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4390 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004391 // Verify that we have at least 1 + NumParams arguments to the builtin.
4392 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004393 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4394 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004395
4396 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004397 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004398 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004399 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4400 // UsualUnaryConversions will convert the function DeclRefExpr into a
4401 // pointer to function.
4402 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004403 const FunctionTypeProto *FnType = 0;
4404 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4405 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004406
4407 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4408 // parameters, and the number of parameters must match the value passed to
4409 // the builtin.
4410 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004411 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4412 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004413
4414 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004415 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004416 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004417 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004418 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004419 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4420 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004421 // Remember our match, and continue processing the remaining arguments
4422 // to catch any errors.
Ted Kremenekfb7413f2009-02-09 17:08:14 +00004423 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor9d293df2008-10-28 00:22:11 +00004424 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004425 BuiltinLoc, RParenLoc);
4426 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004427 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004428 // Return the newly created OverloadExpr node, if we succeded in matching
4429 // exactly one of the candidate functions.
4430 if (OE)
4431 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004432
4433 // If we didn't find a matching function Expr in the __builtin_overload list
4434 // the return an error.
4435 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004436 for (unsigned i = 0; i != NumParams; ++i) {
4437 if (i != 0) typeNames += ", ";
4438 typeNames += Args[i+1]->getType().getAsString();
4439 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004440
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004441 return Diag(BuiltinLoc, diag::err_overload_no_match)
4442 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004443}
4444
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004445Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4446 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004447 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004448 Expr *E = static_cast<Expr*>(expr);
4449 QualType T = QualType::getFromOpaquePtr(type);
4450
4451 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004452
4453 // Get the va_list type
4454 QualType VaListType = Context.getBuiltinVaListType();
4455 // Deal with implicit array decay; for example, on x86-64,
4456 // va_list is an array, but it's supposed to decay to
4457 // a pointer for va_arg.
4458 if (VaListType->isArrayType())
4459 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004460 // Make sure the input expression also decays appropriately.
4461 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004462
4463 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004464 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004465 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004466 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004467
4468 // FIXME: Warn if a non-POD type is passed in.
4469
Steve Naroff6ece14c2009-01-21 00:14:39 +00004470 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004471}
4472
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004473Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4474 // The type of __null will be int or long, depending on the size of
4475 // pointers on the target.
4476 QualType Ty;
4477 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4478 Ty = Context.IntTy;
4479 else
4480 Ty = Context.LongTy;
4481
Steve Naroff6ece14c2009-01-21 00:14:39 +00004482 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004483}
4484
Chris Lattner5cf216b2008-01-04 18:04:52 +00004485bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4486 SourceLocation Loc,
4487 QualType DstType, QualType SrcType,
4488 Expr *SrcExpr, const char *Flavor) {
4489 // Decode the result (notice that AST's are still created for extensions).
4490 bool isInvalid = false;
4491 unsigned DiagKind;
4492 switch (ConvTy) {
4493 default: assert(0 && "Unknown conversion type");
4494 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004495 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004496 DiagKind = diag::ext_typecheck_convert_pointer_int;
4497 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004498 case IntToPointer:
4499 DiagKind = diag::ext_typecheck_convert_int_pointer;
4500 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004501 case IncompatiblePointer:
4502 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4503 break;
4504 case FunctionVoidPointer:
4505 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4506 break;
4507 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004508 // If the qualifiers lost were because we were applying the
4509 // (deprecated) C++ conversion from a string literal to a char*
4510 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4511 // Ideally, this check would be performed in
4512 // CheckPointerTypesForAssignment. However, that would require a
4513 // bit of refactoring (so that the second argument is an
4514 // expression, rather than a type), which should be done as part
4515 // of a larger effort to fix CheckPointerTypesForAssignment for
4516 // C++ semantics.
4517 if (getLangOptions().CPlusPlus &&
4518 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4519 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004520 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4521 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004522 case IntToBlockPointer:
4523 DiagKind = diag::err_int_to_block_pointer;
4524 break;
4525 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004526 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004527 break;
Steve Naroff39579072008-10-14 22:18:38 +00004528 case IncompatibleObjCQualifiedId:
4529 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4530 // it can give a more specific diagnostic.
4531 DiagKind = diag::warn_incompatible_qualified_id;
4532 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004533 case IncompatibleVectors:
4534 DiagKind = diag::warn_incompatible_vectors;
4535 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004536 case Incompatible:
4537 DiagKind = diag::err_typecheck_convert_incompatible;
4538 isInvalid = true;
4539 break;
4540 }
4541
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004542 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4543 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004544 return isInvalid;
4545}
Anders Carlssone21555e2008-11-30 19:50:32 +00004546
4547bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4548{
4549 Expr::EvalResult EvalResult;
4550
4551 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4552 EvalResult.HasSideEffects) {
4553 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4554
4555 if (EvalResult.Diag) {
4556 // We only show the note if it's not the usual "invalid subexpression"
4557 // or if it's actually in a subexpression.
4558 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4559 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4560 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4561 }
4562
4563 return true;
4564 }
4565
4566 if (EvalResult.Diag) {
4567 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4568 E->getSourceRange();
4569
4570 // Print the reason it's not a constant.
4571 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4572 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4573 }
4574
4575 if (Result)
4576 *Result = EvalResult.Val.getInt();
4577 return false;
4578}