blob: 201a0f99e3367e0edc2072b615419c4de06cf2be [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl95216a62009-02-07 00:15:38 +000014#include "SemaInherit.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
Chris Lattner299b8842008-07-25 21:10:04 +000030//===----------------------------------------------------------------------===//
31// Standard Promotions and Conversions
32//===----------------------------------------------------------------------===//
33
Chris Lattner299b8842008-07-25 21:10:04 +000034/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
35void Sema::DefaultFunctionArrayConversion(Expr *&E) {
36 QualType Ty = E->getType();
37 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
38
Chris Lattner299b8842008-07-25 21:10:04 +000039 if (Ty->isFunctionType())
40 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000041 else if (Ty->isArrayType()) {
42 // In C90 mode, arrays only promote to pointers if the array expression is
43 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
44 // type 'array of type' is converted to an expression that has type 'pointer
45 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
46 // that has type 'array of type' ...". The relevant change is "an lvalue"
47 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000048 //
49 // C++ 4.2p1:
50 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
51 // T" can be converted to an rvalue of type "pointer to T".
52 //
53 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
54 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000055 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
56 }
Chris Lattner299b8842008-07-25 21:10:04 +000057}
58
59/// UsualUnaryConversions - Performs various conversions that are common to most
60/// operators (C99 6.3). The conversions of array and function types are
61/// sometimes surpressed. For example, the array->pointer conversion doesn't
62/// apply if the array is an argument to the sizeof or address (&) operators.
63/// In these instances, this routine should *not* be called.
64Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
65 QualType Ty = Expr->getType();
66 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
67
Chris Lattner299b8842008-07-25 21:10:04 +000068 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
69 ImpCastExprToType(Expr, Context.IntTy);
70 else
71 DefaultFunctionArrayConversion(Expr);
72
73 return Expr;
74}
75
Chris Lattner9305c3d2008-07-25 22:25:12 +000076/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
77/// do not have a prototype. Arguments that have type float are promoted to
78/// double. All other argument types are converted by UsualUnaryConversions().
79void Sema::DefaultArgumentPromotion(Expr *&Expr) {
80 QualType Ty = Expr->getType();
81 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
82
83 // If this is a 'float' (CVR qualified or typedef) promote to double.
84 if (const BuiltinType *BT = Ty->getAsBuiltinType())
85 if (BT->getKind() == BuiltinType::Float)
86 return ImpCastExprToType(Expr, Context.DoubleTy);
87
88 UsualUnaryConversions(Expr);
89}
90
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000091// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
92// will warn if the resulting type is not a POD type.
93void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
94
95{
96 DefaultArgumentPromotion(Expr);
97
98 if (!Expr->getType()->isPODType()) {
99 Diag(Expr->getLocStart(),
100 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
101 Expr->getType() << CT;
102 }
103}
104
105
Chris Lattner299b8842008-07-25 21:10:04 +0000106/// UsualArithmeticConversions - Performs various conversions that are common to
107/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
108/// routine returns the first non-arithmetic type found. The client is
109/// responsible for emitting appropriate error diagnostics.
110/// FIXME: verify the conversion rules for "complex int" are consistent with
111/// GCC.
112QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
113 bool isCompAssign) {
114 if (!isCompAssign) {
115 UsualUnaryConversions(lhsExpr);
116 UsualUnaryConversions(rhsExpr);
117 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000118
Chris Lattner299b8842008-07-25 21:10:04 +0000119 // For conversion purposes, we ignore any qualifiers.
120 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000121 QualType lhs =
122 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
123 QualType rhs =
124 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000125
126 // If both types are identical, no conversion is needed.
127 if (lhs == rhs)
128 return lhs;
129
130 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
131 // The caller can deal with this (e.g. pointer + int).
132 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
133 return lhs;
134
135 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
136 if (!isCompAssign) {
137 ImpCastExprToType(lhsExpr, destType);
138 ImpCastExprToType(rhsExpr, destType);
139 }
140 return destType;
141}
142
143QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
144 // Perform the usual unary conversions. We do this early so that
145 // integral promotions to "int" can allow us to exit early, in the
146 // lhs == rhs check. Also, for conversion purposes, we ignore any
147 // qualifiers. For example, "const float" and "float" are
148 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000149 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
150 else lhs = lhs.getUnqualifiedType();
151 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
152 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000153
Chris Lattner299b8842008-07-25 21:10:04 +0000154 // If both types are identical, no conversion is needed.
155 if (lhs == rhs)
156 return lhs;
157
158 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
159 // The caller can deal with this (e.g. pointer + int).
160 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
161 return lhs;
162
163 // At this point, we have two different arithmetic types.
164
165 // Handle complex types first (C99 6.3.1.8p1).
166 if (lhs->isComplexType() || rhs->isComplexType()) {
167 // if we have an integer operand, the result is the complex type.
168 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
169 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000170 return lhs;
171 }
172 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
173 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000174 return rhs;
175 }
176 // This handles complex/complex, complex/float, or float/complex.
177 // When both operands are complex, the shorter operand is converted to the
178 // type of the longer, and that is the type of the result. This corresponds
179 // to what is done when combining two real floating-point operands.
180 // The fun begins when size promotion occur across type domains.
181 // From H&S 6.3.4: When one operand is complex and the other is a real
182 // floating-point type, the less precise type is converted, within it's
183 // real or complex domain, to the precision of the other type. For example,
184 // when combining a "long double" with a "double _Complex", the
185 // "double _Complex" is promoted to "long double _Complex".
186 int result = Context.getFloatingTypeOrder(lhs, rhs);
187
188 if (result > 0) { // The left side is bigger, convert rhs.
189 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000190 } else if (result < 0) { // The right side is bigger, convert lhs.
191 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000192 }
193 // At this point, lhs and rhs have the same rank/size. Now, make sure the
194 // domains match. This is a requirement for our implementation, C99
195 // does not require this promotion.
196 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
197 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return rhs;
199 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000200 return lhs;
201 }
202 }
203 return lhs; // The domain/size match exactly.
204 }
205 // Now handle "real" floating types (i.e. float, double, long double).
206 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
207 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000208 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000209 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000210 return lhs;
211 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000212 if (rhs->isComplexIntegerType()) {
213 // convert rhs to the complex floating point type.
214 return Context.getComplexType(lhs);
215 }
216 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000217 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000218 return rhs;
219 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000220 if (lhs->isComplexIntegerType()) {
221 // convert lhs to the complex floating point type.
222 return Context.getComplexType(rhs);
223 }
Chris Lattner299b8842008-07-25 21:10:04 +0000224 // We have two real floating types, float/complex combos were handled above.
225 // Convert the smaller operand to the bigger result.
226 int result = Context.getFloatingTypeOrder(lhs, rhs);
227
228 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
231 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000232 return rhs;
233 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000234 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000235 }
236 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
237 // Handle GCC complex int extension.
238 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
239 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
240
241 if (lhsComplexInt && rhsComplexInt) {
242 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
243 rhsComplexInt->getElementType()) >= 0) {
244 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000245 return lhs;
246 }
Chris Lattner299b8842008-07-25 21:10:04 +0000247 return rhs;
248 } else if (lhsComplexInt && rhs->isIntegerType()) {
249 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000250 return lhs;
251 } else if (rhsComplexInt && lhs->isIntegerType()) {
252 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000253 return rhs;
254 }
255 }
256 // Finally, we have two differing integer types.
257 // The rules for this case are in C99 6.3.1.8
258 int compare = Context.getIntegerTypeOrder(lhs, rhs);
259 bool lhsSigned = lhs->isSignedIntegerType(),
260 rhsSigned = rhs->isSignedIntegerType();
261 QualType destType;
262 if (lhsSigned == rhsSigned) {
263 // Same signedness; use the higher-ranked type
264 destType = compare >= 0 ? lhs : rhs;
265 } else if (compare != (lhsSigned ? 1 : -1)) {
266 // The unsigned type has greater than or equal rank to the
267 // signed type, so use the unsigned type
268 destType = lhsSigned ? rhs : lhs;
269 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
270 // The two types are different widths; if we are here, that
271 // means the signed type is larger than the unsigned type, so
272 // use the signed type.
273 destType = lhsSigned ? lhs : rhs;
274 } else {
275 // The signed type is higher-ranked than the unsigned type,
276 // but isn't actually any bigger (like unsigned int and long
277 // on most 32-bit systems). Use the unsigned type corresponding
278 // to the signed type.
279 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
280 }
Chris Lattner299b8842008-07-25 21:10:04 +0000281 return destType;
282}
283
284//===----------------------------------------------------------------------===//
285// Semantic Analysis for various Expression Types
286//===----------------------------------------------------------------------===//
287
288
Steve Naroff87d58b42007-09-16 03:34:24 +0000289/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000290/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
291/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
292/// multiple tokens. However, the common case is that StringToks points to one
293/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000294///
295Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000296Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000297 assert(NumStringToks && "Must have at least one string!");
298
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000299 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000300 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000301 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000302
303 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
304 for (unsigned i = 0; i != NumStringToks; ++i)
305 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306
Chris Lattnera6dcce32008-02-11 00:02:17 +0000307 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000308 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000309 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000310
311 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
312 if (getLangOptions().CPlusPlus)
313 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000314
Chris Lattnera6dcce32008-02-11 00:02:17 +0000315 // Get an array type for the string, according to C99 6.4.5. This includes
316 // the nul terminator character as well as the string length for pascal
317 // strings.
318 StrTy = Context.getConstantArrayType(StrTy,
319 llvm::APInt(32, Literal.GetStringLength()+1),
320 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000321
Chris Lattner4b009652007-07-25 00:24:17 +0000322 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000323 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000324 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000325 Literal.AnyWide, StrTy,
326 StringToks[0].getLocation(),
327 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000328}
329
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000330/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
331/// CurBlock to VD should cause it to be snapshotted (as we do for auto
332/// variables defined outside the block) or false if this is not needed (e.g.
333/// for values inside the block or for globals).
334///
335/// FIXME: This will create BlockDeclRefExprs for global variables,
336/// function references, etc which is suboptimal :) and breaks
337/// things like "integer constant expression" tests.
338static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
339 ValueDecl *VD) {
340 // If the value is defined inside the block, we couldn't snapshot it even if
341 // we wanted to.
342 if (CurBlock->TheDecl == VD->getDeclContext())
343 return false;
344
345 // If this is an enum constant or function, it is constant, don't snapshot.
346 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
347 return false;
348
349 // If this is a reference to an extern, static, or global variable, no need to
350 // snapshot it.
351 // FIXME: What about 'const' variables in C++?
352 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
353 return Var->hasLocalStorage();
354
355 return true;
356}
357
358
359
Steve Naroff0acc9c92007-09-15 18:49:24 +0000360/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000361/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000362/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000363/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000364/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000365Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
366 IdentifierInfo &II,
367 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000368 const CXXScopeSpec *SS,
369 bool isAddressOfOperand) {
370 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000371 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000372}
373
Douglas Gregor566782a2009-01-06 05:10:23 +0000374/// BuildDeclRefExpr - Build either a DeclRefExpr or a
375/// QualifiedDeclRefExpr based on whether or not SS is a
376/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000377DeclRefExpr *
378Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
379 bool TypeDependent, bool ValueDependent,
380 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000381 if (SS && !SS->isEmpty())
382 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000383 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000384 else
385 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000386}
387
Douglas Gregor723d3332009-01-07 00:43:41 +0000388/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
389/// variable corresponding to the anonymous union or struct whose type
390/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000391static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000392 assert(Record->isAnonymousStructOrUnion() &&
393 "Record must be an anonymous struct or union!");
394
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000395 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000396 // be an O(1) operation rather than a slow walk through DeclContext's
397 // vector (which itself will be eliminated). DeclGroups might make
398 // this even better.
399 DeclContext *Ctx = Record->getDeclContext();
400 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
401 DEnd = Ctx->decls_end();
402 D != DEnd; ++D) {
403 if (*D == Record) {
404 // The object for the anonymous struct/union directly
405 // follows its type in the list of declarations.
406 ++D;
407 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000408 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000409 return *D;
410 }
411 }
412
413 assert(false && "Missing object for anonymous record");
414 return 0;
415}
416
Sebastian Redlcd883f72009-01-18 18:53:16 +0000417Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000418Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
419 FieldDecl *Field,
420 Expr *BaseObjectExpr,
421 SourceLocation OpLoc) {
422 assert(Field->getDeclContext()->isRecord() &&
423 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
424 && "Field must be stored inside an anonymous struct or union");
425
426 // Construct the sequence of field member references
427 // we'll have to perform to get to the field in the anonymous
428 // union/struct. The list of members is built from the field
429 // outward, so traverse it backwards to go from an object in
430 // the current context to the field we found.
431 llvm::SmallVector<FieldDecl *, 4> AnonFields;
432 AnonFields.push_back(Field);
433 VarDecl *BaseObject = 0;
434 DeclContext *Ctx = Field->getDeclContext();
435 do {
436 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000437 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000438 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
439 AnonFields.push_back(AnonField);
440 else {
441 BaseObject = cast<VarDecl>(AnonObject);
442 break;
443 }
444 Ctx = Ctx->getParent();
445 } while (Ctx->isRecord() &&
446 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
447
448 // Build the expression that refers to the base object, from
449 // which we will build a sequence of member references to each
450 // of the anonymous union objects and, eventually, the field we
451 // found via name lookup.
452 bool BaseObjectIsPointer = false;
453 unsigned ExtraQuals = 0;
454 if (BaseObject) {
455 // BaseObject is an anonymous struct/union variable (and is,
456 // therefore, not part of another non-anonymous record).
457 delete BaseObjectExpr;
458
Steve Naroff774e4152009-01-21 00:14:39 +0000459 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000460 SourceLocation());
461 ExtraQuals
462 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
463 } else if (BaseObjectExpr) {
464 // The caller provided the base object expression. Determine
465 // whether its a pointer and whether it adds any qualifiers to the
466 // anonymous struct/union fields we're looking into.
467 QualType ObjectType = BaseObjectExpr->getType();
468 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
469 BaseObjectIsPointer = true;
470 ObjectType = ObjectPtr->getPointeeType();
471 }
472 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
473 } else {
474 // We've found a member of an anonymous struct/union that is
475 // inside a non-anonymous struct/union, so in a well-formed
476 // program our base object expression is "this".
477 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
478 if (!MD->isStatic()) {
479 QualType AnonFieldType
480 = Context.getTagDeclType(
481 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
482 QualType ThisType = Context.getTagDeclType(MD->getParent());
483 if ((Context.getCanonicalType(AnonFieldType)
484 == Context.getCanonicalType(ThisType)) ||
485 IsDerivedFrom(ThisType, AnonFieldType)) {
486 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000487 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000488 MD->getThisType(Context));
489 BaseObjectIsPointer = true;
490 }
491 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000492 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
493 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000494 }
495 ExtraQuals = MD->getTypeQualifiers();
496 }
497
498 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000499 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
500 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000501 }
502
503 // Build the implicit member references to the field of the
504 // anonymous struct/union.
505 Expr *Result = BaseObjectExpr;
506 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
507 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
508 FI != FIEnd; ++FI) {
509 QualType MemberType = (*FI)->getType();
510 if (!(*FI)->isMutable()) {
511 unsigned combinedQualifiers
512 = MemberType.getCVRQualifiers() | ExtraQuals;
513 MemberType = MemberType.getQualifiedType(combinedQualifiers);
514 }
Steve Naroff774e4152009-01-21 00:14:39 +0000515 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
516 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000517 BaseObjectIsPointer = false;
518 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
519 OpLoc = SourceLocation();
520 }
521
Sebastian Redlcd883f72009-01-18 18:53:16 +0000522 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000523}
524
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000525/// ActOnDeclarationNameExpr - The parser has read some kind of name
526/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
527/// performs lookup on that name and returns an expression that refers
528/// to that name. This routine isn't directly called from the parser,
529/// because the parser doesn't know about DeclarationName. Rather,
530/// this routine is called by ActOnIdentifierExpr,
531/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
532/// which form the DeclarationName from the corresponding syntactic
533/// forms.
534///
535/// HasTrailingLParen indicates whether this identifier is used in a
536/// function call context. LookupCtx is only used for a C++
537/// qualified-id (foo::bar) to indicate the class or namespace that
538/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000539///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000540/// isAddressOfOperand means that this expression is the direct operand
541/// of an address-of operator. This matters because this is the only
542/// situation where a qualified name referencing a non-static member may
543/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000544Sema::OwningExprResult
545Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
546 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000547 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000548 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000549 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000550 if (SS && SS->isInvalid())
551 return ExprError();
552 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000553
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000554 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
555 HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
556 // We've seen something of the form
557 //
558 // identifier(
559 //
560 // and we did not find any entity by the name
561 // "identifier". However, this identifier is still subject to
562 // argument-dependent lookup, so keep track of the name.
563 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
564 Context.OverloadTy,
565 Loc));
566 }
567
Douglas Gregor09be81b2009-02-04 17:27:36 +0000568 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000569 if (Lookup.isAmbiguous()) {
570 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
571 SS && SS->isSet() ? SS->getRange()
572 : SourceRange());
573 return ExprError();
574 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000575 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000576
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000577 // If this reference is in an Objective-C method, then ivar lookup happens as
578 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000579 IdentifierInfo *II = Name.getAsIdentifierInfo();
580 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000581 // There are two cases to handle here. 1) scoped lookup could have failed,
582 // in which case we should look for an ivar. 2) scoped lookup could have
583 // found a decl, but that decl is outside the current method (i.e. a global
584 // variable). In these two cases, we do a lookup for an ivar with this
585 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000586 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000587 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000588 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000589 // FIXME: This should use a new expr for a direct reference, don't turn
590 // this into Self->ivar, just return a BareIVarExpr or something.
591 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000592 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000593 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
594 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000595 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000596 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000597 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000598 }
599 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000600 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000601 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000602 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000603 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000604 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000605 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000606 }
Chris Lattner4b009652007-07-25 00:24:17 +0000607 if (D == 0) {
608 // Otherwise, this could be an implicitly declared function reference (legal
609 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000610 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000611 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000612 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000613 else {
614 // If this name wasn't predeclared and if this is not a function call,
615 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000616 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000617 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
618 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000619 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
620 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000621 return ExprError(Diag(Loc, diag::err_undeclared_use)
622 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000623 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000624 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
626 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000627
Sebastian Redl0c9da212009-02-03 20:19:35 +0000628 // If this is an expression of the form &Class::member, don't build an
629 // implicit member ref, because we want a pointer to the member in general,
630 // not any specific instance's member.
631 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000632 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000633 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000634 QualType DType;
635 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
636 DType = FD->getType().getNonReferenceType();
637 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
638 DType = Method->getType();
639 } else if (isa<OverloadedFunctionDecl>(D)) {
640 DType = Context.OverloadTy;
641 }
642 // Could be an inner type. That's diagnosed below, so ignore it here.
643 if (!DType.isNull()) {
644 // The pointer is type- and value-dependent if it points into something
645 // dependent.
646 bool Dependent = false;
647 for (; DC; DC = DC->getParent()) {
648 // FIXME: could stop early at namespace scope.
649 if (DC->isRecord()) {
650 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
651 if (Context.getTypeDeclType(Record)->isDependentType()) {
652 Dependent = true;
653 break;
654 }
655 }
656 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000657 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000658 }
659 }
660 }
661
Douglas Gregor723d3332009-01-07 00:43:41 +0000662 // We may have found a field within an anonymous union or struct
663 // (C++ [class.union]).
664 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
665 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
666 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000667
Douglas Gregor3257fb52008-12-22 05:46:06 +0000668 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
669 if (!MD->isStatic()) {
670 // C++ [class.mfct.nonstatic]p2:
671 // [...] if name lookup (3.4.1) resolves the name in the
672 // id-expression to a nonstatic nontype member of class X or of
673 // a base class of X, the id-expression is transformed into a
674 // class member access expression (5.2.5) using (*this) (9.3.2)
675 // as the postfix-expression to the left of the '.' operator.
676 DeclContext *Ctx = 0;
677 QualType MemberType;
678 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
679 Ctx = FD->getDeclContext();
680 MemberType = FD->getType();
681
682 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
683 MemberType = RefType->getPointeeType();
684 else if (!FD->isMutable()) {
685 unsigned combinedQualifiers
686 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
687 MemberType = MemberType.getQualifiedType(combinedQualifiers);
688 }
689 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
690 if (!Method->isStatic()) {
691 Ctx = Method->getParent();
692 MemberType = Method->getType();
693 }
694 } else if (OverloadedFunctionDecl *Ovl
695 = dyn_cast<OverloadedFunctionDecl>(D)) {
696 for (OverloadedFunctionDecl::function_iterator
697 Func = Ovl->function_begin(),
698 FuncEnd = Ovl->function_end();
699 Func != FuncEnd; ++Func) {
700 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
701 if (!DMethod->isStatic()) {
702 Ctx = Ovl->getDeclContext();
703 MemberType = Context.OverloadTy;
704 break;
705 }
706 }
707 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000708
709 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000710 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
711 QualType ThisType = Context.getTagDeclType(MD->getParent());
712 if ((Context.getCanonicalType(CtxType)
713 == Context.getCanonicalType(ThisType)) ||
714 IsDerivedFrom(ThisType, CtxType)) {
715 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000716 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000717 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000718 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000719 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000720 }
721 }
722 }
723 }
724
Douglas Gregor8acb7272008-12-11 16:49:14 +0000725 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000726 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
727 if (MD->isStatic())
728 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000729 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
730 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000731 }
732
Douglas Gregor3257fb52008-12-22 05:46:06 +0000733 // Any other ways we could have found the field in a well-formed
734 // program would have been turned into implicit member expressions
735 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000736 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
737 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000738 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000739
Chris Lattner4b009652007-07-25 00:24:17 +0000740 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000741 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000742 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000743 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000744 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000745 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000746
Steve Naroffd6163f32008-09-05 22:11:13 +0000747 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000748 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000749 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
750 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000751
Steve Naroffd6163f32008-09-05 22:11:13 +0000752 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000753
Steve Naroffd6163f32008-09-05 22:11:13 +0000754 // check if referencing an identifier with __attribute__((deprecated)).
755 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000756 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
757
Douglas Gregor48840c72008-12-10 23:01:14 +0000758 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
759 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
760 Scope *CheckS = S;
761 while (CheckS) {
762 if (CheckS->isWithinElse() &&
763 CheckS->getControlParent()->isDeclScope(Var)) {
764 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000765 ExprError(Diag(Loc, diag::warn_value_always_false)
766 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000767 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000768 ExprError(Diag(Loc, diag::warn_value_always_zero)
769 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000770 break;
771 }
772
773 // Move up one more control parent to check again.
774 CheckS = CheckS->getControlParent();
775 if (CheckS)
776 CheckS = CheckS->getParent();
777 }
778 }
779 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000780
781 // Only create DeclRefExpr's for valid Decl's.
782 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000783 return ExprError();
784
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000785 // If the identifier reference is inside a block, and it refers to a value
786 // that is outside the block, create a BlockDeclRefExpr instead of a
787 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
788 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000789 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000790 // We do not do this for things like enum constants, global variables, etc,
791 // as they do not get snapshotted.
792 //
793 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000794 // The BlocksAttr indicates the variable is bound by-reference.
795 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000796 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000797 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000798
Steve Naroff52059382008-10-10 01:28:17 +0000799 // Variable will be bound by-copy, make it const within the closure.
800 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000801 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000802 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000803 }
804 // If this reference is not in a block or if the referenced variable is
805 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000806
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000807 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000808 bool ValueDependent = false;
809 if (getLangOptions().CPlusPlus) {
810 // C++ [temp.dep.expr]p3:
811 // An id-expression is type-dependent if it contains:
812 // - an identifier that was declared with a dependent type,
813 if (VD->getType()->isDependentType())
814 TypeDependent = true;
815 // - FIXME: a template-id that is dependent,
816 // - a conversion-function-id that specifies a dependent type,
817 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
818 Name.getCXXNameType()->isDependentType())
819 TypeDependent = true;
820 // - a nested-name-specifier that contains a class-name that
821 // names a dependent type.
822 else if (SS && !SS->isEmpty()) {
823 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
824 DC; DC = DC->getParent()) {
825 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000826 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000827 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
828 if (Context.getTypeDeclType(Record)->isDependentType()) {
829 TypeDependent = true;
830 break;
831 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000832 }
833 }
834 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000835
Douglas Gregora5d84612008-12-10 20:57:37 +0000836 // C++ [temp.dep.constexpr]p2:
837 //
838 // An identifier is value-dependent if it is:
839 // - a name declared with a dependent type,
840 if (TypeDependent)
841 ValueDependent = true;
842 // - the name of a non-type template parameter,
843 else if (isa<NonTypeTemplateParmDecl>(VD))
844 ValueDependent = true;
845 // - a constant with integral or enumeration type and is
846 // initialized with an expression that is value-dependent
847 // (FIXME!).
848 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000849
Sebastian Redlcd883f72009-01-18 18:53:16 +0000850 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
851 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000852}
853
Sebastian Redlcd883f72009-01-18 18:53:16 +0000854Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
855 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000856 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000857
Chris Lattner4b009652007-07-25 00:24:17 +0000858 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000859 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000860 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
861 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
862 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000863 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000864
Chris Lattner7e637512008-01-12 08:14:25 +0000865 // Pre-defined identifiers are of type char[x], where x is the length of the
866 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000867 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000868 if (FunctionDecl *FD = getCurFunctionDecl())
869 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000870 else if (ObjCMethodDecl *MD = getCurMethodDecl())
871 Length = MD->getSynthesizedMethodSize();
872 else {
873 Diag(Loc, diag::ext_predef_outside_function);
874 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
875 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
876 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000877
878
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000879 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000880 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000881 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000882 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000883}
884
Sebastian Redlcd883f72009-01-18 18:53:16 +0000885Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000886 llvm::SmallString<16> CharBuffer;
887 CharBuffer.resize(Tok.getLength());
888 const char *ThisTokBegin = &CharBuffer[0];
889 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000890
Chris Lattner4b009652007-07-25 00:24:17 +0000891 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
892 Tok.getLocation(), PP);
893 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000894 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000895
896 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
897
Sebastian Redl75324932009-01-20 22:23:13 +0000898 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
899 Literal.isWide(),
900 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000901}
902
Sebastian Redlcd883f72009-01-18 18:53:16 +0000903Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
904 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000905 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
906 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000907 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000908 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000909 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000910 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000911 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000912
Chris Lattner4b009652007-07-25 00:24:17 +0000913 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000914 // Add padding so that NumericLiteralParser can overread by one character.
915 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000916 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000917
Chris Lattner4b009652007-07-25 00:24:17 +0000918 // Get the spelling of the token, which eliminates trigraphs, etc.
919 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000920
Chris Lattner4b009652007-07-25 00:24:17 +0000921 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
922 Tok.getLocation(), PP);
923 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000924 return ExprError();
925
Chris Lattner1de66eb2007-08-26 03:42:43 +0000926 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000927
Chris Lattner1de66eb2007-08-26 03:42:43 +0000928 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000929 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000930 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000931 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000932 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000933 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000934 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000935 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000936
937 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
938
Ted Kremenekddedbe22007-11-29 00:56:49 +0000939 // isExact will be set by GetFloatValue().
940 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000941 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
942 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000943
Chris Lattner1de66eb2007-08-26 03:42:43 +0000944 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000945 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000946 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000947 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000948
Neil Booth7421e9c2007-08-29 22:00:19 +0000949 // long long is a C99 feature.
950 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000951 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000952 Diag(Tok.getLocation(), diag::ext_longlong);
953
Chris Lattner4b009652007-07-25 00:24:17 +0000954 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000955 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000956
Chris Lattner4b009652007-07-25 00:24:17 +0000957 if (Literal.GetIntegerValue(ResultVal)) {
958 // If this value didn't fit into uintmax_t, warn and force to ull.
959 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000960 Ty = Context.UnsignedLongLongTy;
961 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000962 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000963 } else {
964 // If this value fits into a ULL, try to figure out what else it fits into
965 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966
Chris Lattner4b009652007-07-25 00:24:17 +0000967 // Octal, Hexadecimal, and integers with a U suffix are allowed to
968 // be an unsigned int.
969 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
970
971 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000972 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000973 if (!Literal.isLong && !Literal.isLongLong) {
974 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000975 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000976
Chris Lattner4b009652007-07-25 00:24:17 +0000977 // Does it fit in a unsigned int?
978 if (ResultVal.isIntN(IntSize)) {
979 // Does it fit in a signed int?
980 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000981 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000982 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000983 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000984 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000985 }
Chris Lattner4b009652007-07-25 00:24:17 +0000986 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000987
Chris Lattner4b009652007-07-25 00:24:17 +0000988 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000989 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000990 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000991
Chris Lattner4b009652007-07-25 00:24:17 +0000992 // Does it fit in a unsigned long?
993 if (ResultVal.isIntN(LongSize)) {
994 // Does it fit in a signed long?
995 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000996 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000997 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000998 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000999 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001001 }
1002
Chris Lattner4b009652007-07-25 00:24:17 +00001003 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001004 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001005 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001006
Chris Lattner4b009652007-07-25 00:24:17 +00001007 // Does it fit in a unsigned long long?
1008 if (ResultVal.isIntN(LongLongSize)) {
1009 // Does it fit in a signed long long?
1010 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001011 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001012 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001013 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001014 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001015 }
1016 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001017
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // If we still couldn't decide a type, we probably have something that
1019 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001020 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001021 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001022 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001023 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001024 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025
Chris Lattnere4068872008-05-09 05:59:00 +00001026 if (ResultVal.getBitWidth() != Width)
1027 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001028 }
Sebastian Redl75324932009-01-20 22:23:13 +00001029 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001030 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001031
Chris Lattner1de66eb2007-08-26 03:42:43 +00001032 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1033 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001034 Res = new (Context) ImaginaryLiteral(Res,
1035 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001036
1037 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001038}
1039
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1041 SourceLocation R, ExprArg Val) {
1042 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001043 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001044 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001045}
1046
1047/// The UsualUnaryConversions() function is *not* called by this routine.
1048/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001049bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1050 SourceLocation OpLoc,
1051 const SourceRange &ExprRange,
1052 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001053 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001054 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001055 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001056 if (isSizeof)
1057 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1058 return false;
1059 }
1060
1061 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001062 Diag(OpLoc, diag::ext_sizeof_void_type)
1063 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001064 return false;
1065 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001066
Chris Lattner159fe082009-01-24 19:46:37 +00001067 return DiagnoseIncompleteType(OpLoc, exprType,
1068 isSizeof ? diag::err_sizeof_incomplete_type :
1069 diag::err_alignof_incomplete_type,
1070 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001071}
1072
Chris Lattner8d9f7962009-01-24 20:17:12 +00001073bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1074 const SourceRange &ExprRange) {
1075 E = E->IgnoreParens();
1076
1077 // alignof decl is always ok.
1078 if (isa<DeclRefExpr>(E))
1079 return false;
1080
1081 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1082 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1083 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001084 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001085 return true;
1086 }
1087 // Other fields are ok.
1088 return false;
1089 }
1090 }
1091 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1092}
1093
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001094/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1095/// the same for @c alignof and @c __alignof
1096/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001097Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001098Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1099 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001100 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001101 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001102
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001103 QualType ArgTy;
1104 SourceRange Range;
1105 if (isType) {
1106 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1107 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001108
1109 // Verify that the operand is valid.
1110 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1111 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001112 } else {
1113 // Get the end location.
1114 Expr *ArgEx = (Expr *)TyOrEx;
1115 Range = ArgEx->getSourceRange();
1116 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001117
1118 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001119 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001120 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001121 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001122 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1123 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1124 isInvalid = true;
1125 } else {
1126 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1127 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001128
1129 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001130 DeleteExpr(ArgEx);
1131 return ExprError();
1132 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001133 }
1134
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001135 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001136 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001137 Context.getSizeType(), OpLoc,
1138 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001139}
1140
Chris Lattner5110ad52007-08-24 21:41:10 +00001141QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001142 DefaultFunctionArrayConversion(V);
1143
Chris Lattnera16e42d2007-08-26 05:39:26 +00001144 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001145 if (const ComplexType *CT = V->getType()->getAsComplexType())
1146 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001147
1148 // Otherwise they pass through real integer and floating point types here.
1149 if (V->getType()->isArithmeticType())
1150 return V->getType();
1151
1152 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001153 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001154 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001155}
1156
1157
Chris Lattner4b009652007-07-25 00:24:17 +00001158
Sebastian Redl8b769972009-01-19 00:08:26 +00001159Action::OwningExprResult
1160Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1161 tok::TokenKind Kind, ExprArg Input) {
1162 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001163
Chris Lattner4b009652007-07-25 00:24:17 +00001164 UnaryOperator::Opcode Opc;
1165 switch (Kind) {
1166 default: assert(0 && "Unknown unary op!");
1167 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1168 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1169 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001170
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001171 if (getLangOptions().CPlusPlus &&
1172 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1173 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001174 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001175 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1176
1177 // C++ [over.inc]p1:
1178 //
1179 // [...] If the function is a member function with one
1180 // parameter (which shall be of type int) or a non-member
1181 // function with two parameters (the second of which shall be
1182 // of type int), it defines the postfix increment operator ++
1183 // for objects of that type. When the postfix increment is
1184 // called as a result of using the ++ operator, the int
1185 // argument will have value zero.
1186 Expr *Args[2] = {
1187 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001188 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1189 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001190 };
1191
1192 // Build the candidate set for overloading
1193 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001194 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1195 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001196
1197 // Perform overload resolution.
1198 OverloadCandidateSet::iterator Best;
1199 switch (BestViableFunction(CandidateSet, Best)) {
1200 case OR_Success: {
1201 // We found a built-in operator or an overloaded operator.
1202 FunctionDecl *FnDecl = Best->Function;
1203
1204 if (FnDecl) {
1205 // We matched an overloaded operator. Build a call to that
1206 // operator.
1207
1208 // Convert the arguments.
1209 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1210 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001211 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001212 } else {
1213 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001214 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001215 FnDecl->getParamDecl(0)->getType(),
1216 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001217 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001218 }
1219
1220 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001221 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001222 = FnDecl->getType()->getAsFunctionType()->getResultType();
1223 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001224
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001225 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001226 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001227 SourceLocation());
1228 UsualUnaryConversions(FnExpr);
1229
Sebastian Redl8b769972009-01-19 00:08:26 +00001230 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001231 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroffe5f128a2009-01-20 19:53:53 +00001232 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001233 } else {
1234 // We matched a built-in operator. Convert the arguments, then
1235 // break out so that we will build the appropriate built-in
1236 // operator node.
1237 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1238 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001239 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001240
1241 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001242 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001243 }
1244
1245 case OR_No_Viable_Function:
1246 // No viable function; fall through to handling this as a
1247 // built-in operator, which will produce an error message for us.
1248 break;
1249
1250 case OR_Ambiguous:
1251 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1252 << UnaryOperator::getOpcodeStr(Opc)
1253 << Arg->getSourceRange();
1254 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001255 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001256 }
1257
1258 // Either we found no viable overloaded operator or we matched a
1259 // built-in operator. In either case, fall through to trying to
1260 // build a built-in operation.
1261 }
1262
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001263 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1264 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001265 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001266 return ExprError();
1267 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001268 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001269}
1270
Sebastian Redl8b769972009-01-19 00:08:26 +00001271Action::OwningExprResult
1272Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1273 ExprArg Idx, SourceLocation RLoc) {
1274 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1275 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001276
Douglas Gregor80723c52008-11-19 17:17:41 +00001277 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001278 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001279 LHSExp->getType()->isEnumeralType() ||
1280 RHSExp->getType()->isRecordType() ||
1281 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001282 // Add the appropriate overloaded operators (C++ [over.match.oper])
1283 // to the candidate set.
1284 OverloadCandidateSet CandidateSet;
1285 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001286 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1287 SourceRange(LLoc, RLoc)))
1288 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001289
Douglas Gregor80723c52008-11-19 17:17:41 +00001290 // Perform overload resolution.
1291 OverloadCandidateSet::iterator Best;
1292 switch (BestViableFunction(CandidateSet, Best)) {
1293 case OR_Success: {
1294 // We found a built-in operator or an overloaded operator.
1295 FunctionDecl *FnDecl = Best->Function;
1296
1297 if (FnDecl) {
1298 // We matched an overloaded operator. Build a call to that
1299 // operator.
1300
1301 // Convert the arguments.
1302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1303 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1304 PerformCopyInitialization(RHSExp,
1305 FnDecl->getParamDecl(0)->getType(),
1306 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001307 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001308 } else {
1309 // Convert the arguments.
1310 if (PerformCopyInitialization(LHSExp,
1311 FnDecl->getParamDecl(0)->getType(),
1312 "passing") ||
1313 PerformCopyInitialization(RHSExp,
1314 FnDecl->getParamDecl(1)->getType(),
1315 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001316 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001317 }
1318
1319 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001320 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001321 = FnDecl->getType()->getAsFunctionType()->getResultType();
1322 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001323
Douglas Gregor80723c52008-11-19 17:17:41 +00001324 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001325 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001326 SourceLocation());
1327 UsualUnaryConversions(FnExpr);
1328
Sebastian Redl8b769972009-01-19 00:08:26 +00001329 Base.release();
1330 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001331 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1332 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001333 } else {
1334 // We matched a built-in operator. Convert the arguments, then
1335 // break out so that we will build the appropriate built-in
1336 // operator node.
1337 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1338 "passing") ||
1339 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1340 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001341 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001342
1343 break;
1344 }
1345 }
1346
1347 case OR_No_Viable_Function:
1348 // No viable function; fall through to handling this as a
1349 // built-in operator, which will produce an error message for us.
1350 break;
1351
1352 case OR_Ambiguous:
1353 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1354 << "[]"
1355 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1356 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001357 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001358 }
1359
1360 // Either we found no viable overloaded operator or we matched a
1361 // built-in operator. In either case, fall through to trying to
1362 // build a built-in operation.
1363 }
1364
Chris Lattner4b009652007-07-25 00:24:17 +00001365 // Perform default conversions.
1366 DefaultFunctionArrayConversion(LHSExp);
1367 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001368
Chris Lattner4b009652007-07-25 00:24:17 +00001369 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1370
1371 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001372 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // in the subscript position. As a result, we need to derive the array base
1374 // and index from the expression types.
1375 Expr *BaseExpr, *IndexExpr;
1376 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001377 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001378 BaseExpr = LHSExp;
1379 IndexExpr = RHSExp;
1380 // FIXME: need to deal with const...
1381 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001382 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001383 // Handle the uncommon case of "123[Ptr]".
1384 BaseExpr = RHSExp;
1385 IndexExpr = LHSExp;
1386 // FIXME: need to deal with const...
1387 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001388 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1389 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001390 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001391
Chris Lattner4b009652007-07-25 00:24:17 +00001392 // FIXME: need to deal with const...
1393 ResultType = VTy->getElementType();
1394 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001395 return ExprError(Diag(LHSExp->getLocStart(),
1396 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1397 }
Chris Lattner4b009652007-07-25 00:24:17 +00001398 // C99 6.5.2.1p1
1399 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001400 return ExprError(Diag(IndexExpr->getLocStart(),
1401 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001402
1403 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1404 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001405 // void (*)(int)) and pointers to incomplete types. Functions are not
1406 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001407 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001408 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001409 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001410 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001411
Sebastian Redl8b769972009-01-19 00:08:26 +00001412 Base.release();
1413 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001414 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1415 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001416}
1417
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001418QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001419CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001420 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001421 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001422
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001423 // The vector accessor can't exceed the number of elements.
1424 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001425
1426 // This flag determines whether or not the component is one of the four
1427 // special names that indicate a subset of exactly half the elements are
1428 // to be selected.
1429 bool HalvingSwizzle = false;
1430
1431 // This flag determines whether or not CompName has an 's' char prefix,
1432 // indicating that it is a string of hex values to be used as vector indices.
1433 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001434
1435 // Check that we've found one of the special components, or that the component
1436 // names must come from the same set.
1437 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001438 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1439 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001440 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001441 do
1442 compStr++;
1443 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001444 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001445 do
1446 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001447 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001448 }
Nate Begeman1486b502009-01-18 01:47:54 +00001449
1450 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001451 // We didn't get to the end of the string. This means the component names
1452 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001453 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1454 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001455 return QualType();
1456 }
Nate Begeman1486b502009-01-18 01:47:54 +00001457
1458 // Ensure no component accessor exceeds the width of the vector type it
1459 // operates on.
1460 if (!HalvingSwizzle) {
1461 compStr = CompName.getName();
1462
1463 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001464 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001465
1466 while (*compStr) {
1467 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1468 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1469 << baseType << SourceRange(CompLoc);
1470 return QualType();
1471 }
1472 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001473 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001474
Nate Begeman1486b502009-01-18 01:47:54 +00001475 // If this is a halving swizzle, verify that the base type has an even
1476 // number of elements.
1477 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001478 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001479 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001480 return QualType();
1481 }
1482
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001483 // The component accessor looks fine - now we need to compute the actual type.
1484 // The vector type is implied by the component accessor. For example,
1485 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001486 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001487 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001488 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1489 : CompName.getLength();
1490 if (HexSwizzle)
1491 CompSize--;
1492
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001493 if (CompSize == 1)
1494 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001495
Nate Begemanaf6ed502008-04-18 23:10:10 +00001496 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001497 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001498 // diagostics look bad. We want extended vector types to appear built-in.
1499 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1500 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1501 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001502 }
1503 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001504}
1505
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001506/// constructSetterName - Return the setter name for the given
1507/// identifier, i.e. "set" + Name where the initial character of Name
1508/// has been capitalized.
1509// FIXME: Merge with same routine in Parser. But where should this
1510// live?
1511static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1512 const IdentifierInfo *Name) {
1513 llvm::SmallString<100> SelectorName;
1514 SelectorName = "set";
1515 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1516 SelectorName[3] = toupper(SelectorName[3]);
1517 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1518}
1519
Sebastian Redl8b769972009-01-19 00:08:26 +00001520Action::OwningExprResult
1521Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1522 tok::TokenKind OpKind, SourceLocation MemberLoc,
1523 IdentifierInfo &Member) {
1524 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001525 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001526
1527 // Perform default conversions.
1528 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001529
Steve Naroff2cb66382007-07-26 03:11:44 +00001530 QualType BaseType = BaseExpr->getType();
1531 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001532
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001533 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1534 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001535 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001536 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001537 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001538 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1540 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001541 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 return ExprError(Diag(MemberLoc,
1543 diag::err_typecheck_member_reference_arrow)
1544 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001545 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001546
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001547 // Handle field access to simple records. This also handles access to fields
1548 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001549 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001550 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001551 if (DiagnoseIncompleteType(OpLoc, BaseType,
1552 diag::err_typecheck_incomplete_tag,
1553 BaseExpr->getSourceRange()))
1554 return ExprError();
1555
Steve Naroff2cb66382007-07-26 03:11:44 +00001556 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001557 // FIXME: Qualified name lookup for C++ is a bit more complicated
1558 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001559 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001560 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001561 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001562
Douglas Gregor09be81b2009-02-04 17:27:36 +00001563 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001564 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001565 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1566 << &Member << BaseExpr->getSourceRange());
1567 else if (Result.isAmbiguous()) {
1568 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1569 MemberLoc, BaseExpr->getSourceRange());
1570 return ExprError();
1571 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001572 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001573
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001574 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001575 // We may have found a field within an anonymous union or struct
1576 // (C++ [class.union]).
1577 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001578 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001579 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001580
Douglas Gregor82d44772008-12-20 23:49:58 +00001581 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1582 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001583 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001584 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1585 MemberType = Ref->getPointeeType();
1586 else {
1587 unsigned combinedQualifiers =
1588 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001589 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001590 combinedQualifiers &= ~QualType::Const;
1591 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1592 }
Eli Friedman76b49832008-02-06 22:48:16 +00001593
Steve Naroff774e4152009-01-21 00:14:39 +00001594 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1595 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001596 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001597 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001598 Var, MemberLoc,
1599 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001600 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001601 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1602 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001603 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001604 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001605 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001606 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001607 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001608 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001609 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001610 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001611 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1612 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001613
Douglas Gregor82d44772008-12-20 23:49:58 +00001614 // We found a declaration kind that we didn't expect. This is a
1615 // generic error message that tells the user that she can't refer
1616 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001617 return ExprError(Diag(MemberLoc,
1618 diag::err_typecheck_member_reference_unknown)
1619 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001620 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001621
Chris Lattnere9d71612008-07-21 04:59:05 +00001622 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1623 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001624 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001625 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001626 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1627 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001628 OpKind == tok::arrow);
1629 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001630 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001631 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001632 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1633 << IFTy->getDecl()->getDeclName() << &Member
1634 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001635 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001636
Chris Lattnere9d71612008-07-21 04:59:05 +00001637 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1638 // pointer to a (potentially qualified) interface type.
1639 const PointerType *PTy;
1640 const ObjCInterfaceType *IFTy;
1641 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1642 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1643 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001644
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001645 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001646 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001647 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001648 MemberLoc, BaseExpr));
1649
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001650 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001651 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1652 E = IFTy->qual_end(); I != E; ++I)
1653 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001654 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001656
1657 // If that failed, look for an "implicit" property by seeing if the nullary
1658 // selector is implemented.
1659
1660 // FIXME: The logic for looking up nullary and unary selectors should be
1661 // shared with the code in ActOnInstanceMessage.
1662
1663 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1664 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001665
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001666 // If this reference is in an @implementation, check for 'private' methods.
1667 if (!Getter)
1668 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1669 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1670 if (ObjCImplementationDecl *ImpDecl =
1671 ObjCImplementations[ClassDecl->getIdentifier()])
1672 Getter = ImpDecl->getInstanceMethod(Sel);
1673
Steve Naroff04151f32008-10-22 19:16:27 +00001674 // Look through local category implementations associated with the class.
1675 if (!Getter) {
1676 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1677 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1678 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1679 }
1680 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001681 if (Getter) {
1682 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001683 // will look for the matching setter, in case it is needed.
1684 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1685 &Member);
1686 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1687 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1688 if (!Setter) {
1689 // If this reference is in an @implementation, also check for 'private'
1690 // methods.
1691 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1692 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1693 if (ObjCImplementationDecl *ImpDecl =
1694 ObjCImplementations[ClassDecl->getIdentifier()])
1695 Setter = ImpDecl->getInstanceMethod(SetterSel);
1696 }
1697 // Look through local category implementations associated with the class.
1698 if (!Setter) {
1699 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1700 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1701 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1702 }
1703 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001704
1705 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001706 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1707 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001708 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001709
1710 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1711 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001712 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001713 // Handle properties on qualified "id" protocols.
1714 const ObjCQualifiedIdType *QIdTy;
1715 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1716 // Check protocols on qualified interfaces.
1717 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001718 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001719 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001720 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001721 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001722 // Also must look for a getter name which uses property syntax.
1723 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1724 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001725 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1726 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001727 }
1728 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001729
1730 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1731 << &Member << BaseType);
1732 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001733 // Handle 'field access' to vectors, such as 'V.xx'.
1734 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001735 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1736 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001737 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001738 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1739 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001740 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001741
1742 return ExprError(Diag(MemberLoc,
1743 diag::err_typecheck_member_reference_struct_union)
1744 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001745}
1746
Douglas Gregor3257fb52008-12-22 05:46:06 +00001747/// ConvertArgumentsForCall - Converts the arguments specified in
1748/// Args/NumArgs to the parameter types of the function FDecl with
1749/// function prototype Proto. Call is the call expression itself, and
1750/// Fn is the function expression. For a C++ member function, this
1751/// routine does not attempt to convert the object argument. Returns
1752/// true if the call is ill-formed.
1753bool
1754Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1755 FunctionDecl *FDecl,
1756 const FunctionTypeProto *Proto,
1757 Expr **Args, unsigned NumArgs,
1758 SourceLocation RParenLoc) {
1759 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1760 // assignment, to the types of the corresponding parameter, ...
1761 unsigned NumArgsInProto = Proto->getNumArgs();
1762 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001763 bool Invalid = false;
1764
Douglas Gregor3257fb52008-12-22 05:46:06 +00001765 // If too few arguments are available (and we don't have default
1766 // arguments for the remaining parameters), don't make the call.
1767 if (NumArgs < NumArgsInProto) {
1768 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1769 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1770 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1771 // Use default arguments for missing arguments
1772 NumArgsToCheck = NumArgsInProto;
1773 Call->setNumArgs(NumArgsInProto);
1774 }
1775
1776 // If too many are passed and not variadic, error on the extras and drop
1777 // them.
1778 if (NumArgs > NumArgsInProto) {
1779 if (!Proto->isVariadic()) {
1780 Diag(Args[NumArgsInProto]->getLocStart(),
1781 diag::err_typecheck_call_too_many_args)
1782 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1783 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1784 Args[NumArgs-1]->getLocEnd());
1785 // This deletes the extra arguments.
1786 Call->setNumArgs(NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001787 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001788 }
1789 NumArgsToCheck = NumArgsInProto;
1790 }
1791
1792 // Continue to check argument types (even if we have too few/many args).
1793 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1794 QualType ProtoArgType = Proto->getArgType(i);
1795
1796 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001797 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001798 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001799
1800 // Pass the argument.
1801 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1802 return true;
1803 } else
1804 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001805 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001806 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001807
Douglas Gregor3257fb52008-12-22 05:46:06 +00001808 Call->setArg(i, Arg);
1809 }
1810
1811 // If this is a variadic call, handle args passed through "...".
1812 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001813 VariadicCallType CallType = VariadicFunction;
1814 if (Fn->getType()->isBlockPointerType())
1815 CallType = VariadicBlock; // Block
1816 else if (isa<MemberExpr>(Fn))
1817 CallType = VariadicMethod;
1818
Douglas Gregor3257fb52008-12-22 05:46:06 +00001819 // Promote the arguments (C99 6.5.2.2p7).
1820 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1821 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001822 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001823 Call->setArg(i, Arg);
1824 }
1825 }
1826
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001827 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001828}
1829
Steve Naroff87d58b42007-09-16 03:34:24 +00001830/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001831/// This provides the location of the left/right parens and a list of comma
1832/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001833Action::OwningExprResult
1834Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1835 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001836 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001837 unsigned NumArgs = args.size();
1838 Expr *Fn = static_cast<Expr *>(fn.release());
1839 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001840 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001841 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001842 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001843
Douglas Gregor3257fb52008-12-22 05:46:06 +00001844 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001845 // Determine whether this is a dependent call inside a C++ template,
1846 // in which case we won't do any semantic analysis now.
1847 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1848 bool Dependent = false;
1849 if (Fn->isTypeDependent())
1850 Dependent = true;
1851 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1852 Dependent = true;
1853
1854 if (Dependent)
1855 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1856 Context.DependentTy, RParenLoc));
1857
1858 // Determine whether this is a call to an object (C++ [over.call.object]).
1859 if (Fn->getType()->isRecordType())
1860 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1861 CommaLocs, RParenLoc));
1862
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001863 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001864 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1865 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1866 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001867 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1868 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001869 }
1870
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001871 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001872 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001873 Expr *FnExpr = Fn;
1874 bool ADL = true;
1875 while (true) {
1876 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1877 FnExpr = IcExpr->getSubExpr();
1878 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001879 // Parentheses around a function disable ADL
1880 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001881 ADL = false;
1882 FnExpr = PExpr->getSubExpr();
1883 } else if (isa<UnaryOperator>(FnExpr) &&
1884 cast<UnaryOperator>(FnExpr)->getOpcode()
1885 == UnaryOperator::AddrOf) {
1886 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
1887 } else {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001888 if (isa<DeclRefExpr>(FnExpr)) {
1889 DRExpr = cast<DeclRefExpr>(FnExpr);
1890
1891 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1892 ADL = ADL && !isa<QualifiedDeclRefExpr>(DRExpr);
1893 }
1894 else if (UnresolvedFunctionNameExpr *DepName
1895 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr))
1896 UnqualifiedName = DepName->getName();
1897 else {
1898 // Any kind of name that does not refer to a declaration (or
1899 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1900 ADL = false;
1901 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001902 break;
1903 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001904 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001905
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001906 OverloadedFunctionDecl *Ovl = 0;
1907 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001908 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001909 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1910 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001911
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001912 if (getLangOptions().CPlusPlus && (FDecl || Ovl || UnqualifiedName)) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001913 // We don't perform ADL for builtins.
1914 if (FDecl && FDecl->getIdentifier() &&
1915 FDecl->getIdentifier()->getBuiltinID())
1916 ADL = false;
1917
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001918 if (Ovl || ADL) {
1919 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1920 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001921 NumArgs, CommaLocs, RParenLoc, ADL);
1922 if (!FDecl)
1923 return ExprError();
1924
1925 // Update Fn to refer to the actual function selected.
1926 Expr *NewFn = 0;
1927 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001928 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001929 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1930 QDRExpr->getLocation(),
1931 false, false,
1932 QDRExpr->getSourceRange().getBegin());
1933 else
1934 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1935 Fn->getSourceRange().getBegin());
1936 Fn->Destroy(Context);
1937 Fn = NewFn;
1938 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001939 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001940
1941 // Promote the function operand.
1942 UsualUnaryConversions(Fn);
1943
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001944 // Make the call expr early, before semantic checks. This guarantees cleanup
1945 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001946 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1947 // Destroy(), or nothing gets cleaned up.
Steve Naroff774e4152009-01-21 00:14:39 +00001948 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001949 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001950
Steve Naroffd6163f32008-09-05 22:11:13 +00001951 const FunctionType *FuncT;
1952 if (!Fn->getType()->isBlockPointerType()) {
1953 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1954 // have type pointer to function".
1955 const PointerType *PT = Fn->getType()->getAsPointerType();
1956 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001957 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1958 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001959 FuncT = PT->getPointeeType()->getAsFunctionType();
1960 } else { // This is a block call.
1961 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1962 getAsFunctionType();
1963 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001964 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001965 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1966 << Fn->getType() << Fn->getSourceRange());
1967
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001968 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001969 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001970
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001971 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001972 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1973 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001974 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001975 } else {
1976 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001977
Steve Naroffdb65e052007-08-28 23:30:39 +00001978 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001979 for (unsigned i = 0; i != NumArgs; i++) {
1980 Expr *Arg = Args[i];
1981 DefaultArgumentPromotion(Arg);
1982 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001983 }
Chris Lattner4b009652007-07-25 00:24:17 +00001984 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001985
Douglas Gregor3257fb52008-12-22 05:46:06 +00001986 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1987 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001988 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1989 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001990
Chris Lattner2e64c072007-08-10 20:18:51 +00001991 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001992 if (FDecl)
1993 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001994
Sebastian Redl8b769972009-01-19 00:08:26 +00001995 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001996}
1997
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001998Action::OwningExprResult
1999Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2000 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002001 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002002 QualType literalType = QualType::getFromOpaquePtr(Ty);
2003 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002004 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002005 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002006
Eli Friedman8c2173d2008-05-20 05:22:08 +00002007 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002008 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002009 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2010 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002011 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2012 diag::err_typecheck_decl_incomplete_type,
2013 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002014 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002015
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002016 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002017 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002018 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002019
Chris Lattnere5cb5862008-12-04 23:50:19 +00002020 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002021 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002022 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002023 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002024 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002025 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002026 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2027 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002028}
2029
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002030Action::OwningExprResult
2031Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2032 InitListDesignations &Designators,
2033 SourceLocation RBraceLoc) {
2034 unsigned NumInit = initlist.size();
2035 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002036
Steve Naroff0acc9c92007-09-15 18:49:24 +00002037 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002038 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002039
Steve Naroff774e4152009-01-21 00:14:39 +00002040 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002041 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002042 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002043 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002044}
2045
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002046/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002047bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002048 UsualUnaryConversions(castExpr);
2049
2050 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2051 // type needs to be scalar.
2052 if (castType->isVoidType()) {
2053 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002054 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2055 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002056 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002057 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2058 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2059 (castType->isStructureType() || castType->isUnionType())) {
2060 // GCC struct/union extension: allow cast to self.
2061 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2062 << castType << castExpr->getSourceRange();
2063 } else if (castType->isUnionType()) {
2064 // GCC cast to union extension
2065 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2066 RecordDecl::field_iterator Field, FieldEnd;
2067 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2068 Field != FieldEnd; ++Field) {
2069 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2070 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2071 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2072 << castExpr->getSourceRange();
2073 break;
2074 }
2075 }
2076 if (Field == FieldEnd)
2077 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2078 << castExpr->getType() << castExpr->getSourceRange();
2079 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002080 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002081 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002082 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002083 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002084 } else if (!castExpr->getType()->isScalarType() &&
2085 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002086 return Diag(castExpr->getLocStart(),
2087 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002088 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002089 } else if (castExpr->getType()->isVectorType()) {
2090 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2091 return true;
2092 } else if (castType->isVectorType()) {
2093 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2094 return true;
2095 }
2096 return false;
2097}
2098
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002099bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002100 assert(VectorTy->isVectorType() && "Not a vector type!");
2101
2102 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002103 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002104 return Diag(R.getBegin(),
2105 Ty->isVectorType() ?
2106 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002107 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002108 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002109 } else
2110 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002111 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002112 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002113
2114 return false;
2115}
2116
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002117Action::OwningExprResult
2118Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2119 SourceLocation RParenLoc, ExprArg Op) {
2120 assert((Ty != 0) && (Op.get() != 0) &&
2121 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002122
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002123 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002124 QualType castType = QualType::getFromOpaquePtr(Ty);
2125
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002126 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002127 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002128 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002129 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002130}
2131
Chris Lattner98a425c2007-11-26 01:40:58 +00002132/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2133/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002134inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2135 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2136 UsualUnaryConversions(cond);
2137 UsualUnaryConversions(lex);
2138 UsualUnaryConversions(rex);
2139 QualType condT = cond->getType();
2140 QualType lexT = lex->getType();
2141 QualType rexT = rex->getType();
2142
2143 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002144 if (!cond->isTypeDependent()) {
2145 if (!condT->isScalarType()) { // C99 6.5.15p2
2146 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2147 return QualType();
2148 }
Chris Lattner4b009652007-07-25 00:24:17 +00002149 }
Chris Lattner992ae932008-01-06 22:42:25 +00002150
2151 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002152 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2153 return Context.DependentTy;
2154
Chris Lattner992ae932008-01-06 22:42:25 +00002155 // If both operands have arithmetic type, do the usual arithmetic conversions
2156 // to find a common type: C99 6.5.15p3,5.
2157 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002158 UsualArithmeticConversions(lex, rex);
2159 return lex->getType();
2160 }
Chris Lattner992ae932008-01-06 22:42:25 +00002161
2162 // If both operands are the same structure or union type, the result is that
2163 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002164 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002165 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002166 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002167 // "If both the operands have structure or union type, the result has
2168 // that type." This implies that CV qualifiers are dropped.
2169 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002170 }
Chris Lattner992ae932008-01-06 22:42:25 +00002171
2172 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002173 // The following || allows only one side to be void (a GCC-ism).
2174 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002175 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002176 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2177 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002178 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002179 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2180 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002181 ImpCastExprToType(lex, Context.VoidTy);
2182 ImpCastExprToType(rex, Context.VoidTy);
2183 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002184 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002185 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2186 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002187 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2188 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002189 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002190 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002191 return lexT;
2192 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002193 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2194 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002195 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002196 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002197 return rexT;
2198 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002199 // Handle the case where both operands are pointers before we handle null
2200 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002201 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2202 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2203 // get the "pointed to" types
2204 QualType lhptee = LHSPT->getPointeeType();
2205 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002206
Chris Lattner71225142007-07-31 21:27:01 +00002207 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2208 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002209 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002210 // Figure out necessary qualifiers (C99 6.5.15p6)
2211 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002212 QualType destType = Context.getPointerType(destPointee);
2213 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2214 ImpCastExprToType(rex, destType); // promote to void*
2215 return destType;
2216 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002217 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002218 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002219 QualType destType = Context.getPointerType(destPointee);
2220 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2221 ImpCastExprToType(rex, destType); // promote to void*
2222 return destType;
2223 }
Chris Lattner4b009652007-07-25 00:24:17 +00002224
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002225 QualType compositeType = lexT;
2226
2227 // If either type is an Objective-C object type then check
2228 // compatibility according to Objective-C.
2229 if (Context.isObjCObjectPointerType(lexT) ||
2230 Context.isObjCObjectPointerType(rexT)) {
2231 // If both operands are interfaces and either operand can be
2232 // assigned to the other, use that type as the composite
2233 // type. This allows
2234 // xxx ? (A*) a : (B*) b
2235 // where B is a subclass of A.
2236 //
2237 // Additionally, as for assignment, if either type is 'id'
2238 // allow silent coercion. Finally, if the types are
2239 // incompatible then make sure to use 'id' as the composite
2240 // type so the result is acceptable for sending messages to.
2241
2242 // FIXME: This code should not be localized to here. Also this
2243 // should use a compatible check instead of abusing the
2244 // canAssignObjCInterfaces code.
2245 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2246 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2247 if (LHSIface && RHSIface &&
2248 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2249 compositeType = lexT;
2250 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002251 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002252 compositeType = rexT;
2253 } else if (Context.isObjCIdType(lhptee) ||
2254 Context.isObjCIdType(rhptee)) {
2255 // FIXME: This code looks wrong, because isObjCIdType checks
2256 // the struct but getObjCIdType returns the pointer to
2257 // struct. This is horrible and should be fixed.
2258 compositeType = Context.getObjCIdType();
2259 } else {
2260 QualType incompatTy = Context.getObjCIdType();
2261 ImpCastExprToType(lex, incompatTy);
2262 ImpCastExprToType(rex, incompatTy);
2263 return incompatTy;
2264 }
2265 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2266 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002267 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002268 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002269 // In this situation, we assume void* type. No especially good
2270 // reason, but this is what gcc does, and we do have to pick
2271 // to get a consistent AST.
2272 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002273 ImpCastExprToType(lex, incompatTy);
2274 ImpCastExprToType(rex, incompatTy);
2275 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002276 }
2277 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002278 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2279 // differently qualified versions of compatible types, the result type is
2280 // a pointer to an appropriately qualified version of the *composite*
2281 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002282 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002283 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002284 ImpCastExprToType(lex, compositeType);
2285 ImpCastExprToType(rex, compositeType);
2286 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002287 }
Chris Lattner4b009652007-07-25 00:24:17 +00002288 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002289 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2290 // evaluates to "struct objc_object *" (and is handled above when comparing
2291 // id with statically typed objects).
2292 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2293 // GCC allows qualified id and any Objective-C type to devolve to
2294 // id. Currently localizing to here until clear this should be
2295 // part of ObjCQualifiedIdTypesAreCompatible.
2296 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2297 (lexT->isObjCQualifiedIdType() &&
2298 Context.isObjCObjectPointerType(rexT)) ||
2299 (rexT->isObjCQualifiedIdType() &&
2300 Context.isObjCObjectPointerType(lexT))) {
2301 // FIXME: This is not the correct composite type. This only
2302 // happens to work because id can more or less be used anywhere,
2303 // however this may change the type of method sends.
2304 // FIXME: gcc adds some type-checking of the arguments and emits
2305 // (confusing) incompatible comparison warnings in some
2306 // cases. Investigate.
2307 QualType compositeType = Context.getObjCIdType();
2308 ImpCastExprToType(lex, compositeType);
2309 ImpCastExprToType(rex, compositeType);
2310 return compositeType;
2311 }
2312 }
2313
Steve Naroff3eac7692008-09-10 19:17:48 +00002314 // Selection between block pointer types is ok as long as they are the same.
2315 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2316 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2317 return lexT;
2318
Chris Lattner992ae932008-01-06 22:42:25 +00002319 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002320 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002321 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002322 return QualType();
2323}
2324
Steve Naroff87d58b42007-09-16 03:34:24 +00002325/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002326/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002327Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2328 SourceLocation ColonLoc,
2329 ExprArg Cond, ExprArg LHS,
2330 ExprArg RHS) {
2331 Expr *CondExpr = (Expr *) Cond.get();
2332 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002333
2334 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2335 // was the condition.
2336 bool isLHSNull = LHSExpr == 0;
2337 if (isLHSNull)
2338 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002339
2340 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002341 RHSExpr, QuestionLoc);
2342 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002343 return ExprError();
2344
2345 Cond.release();
2346 LHS.release();
2347 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002348 return Owned(new (Context) ConditionalOperator(CondExpr,
2349 isLHSNull ? 0 : LHSExpr,
2350 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002351}
2352
Chris Lattner4b009652007-07-25 00:24:17 +00002353
2354// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2355// being closely modeled after the C99 spec:-). The odd characteristic of this
2356// routine is it effectively iqnores the qualifiers on the top level pointee.
2357// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2358// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002359Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002360Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2361 QualType lhptee, rhptee;
2362
2363 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002364 lhptee = lhsType->getAsPointerType()->getPointeeType();
2365 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002366
2367 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002368 lhptee = Context.getCanonicalType(lhptee);
2369 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002370
Chris Lattner005ed752008-01-04 18:04:52 +00002371 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002372
2373 // C99 6.5.16.1p1: This following citation is common to constraints
2374 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2375 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002376 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002377 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002378 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002379
2380 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2381 // incomplete type and the other is a pointer to a qualified or unqualified
2382 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002383 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002384 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002385 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002386
2387 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002388 assert(rhptee->isFunctionType());
2389 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002390 }
2391
2392 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002393 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002394 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002395
2396 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002397 assert(lhptee->isFunctionType());
2398 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002399 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002400
2401 // Check for ObjC interfaces
2402 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2403 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2404 if (LHSIface && RHSIface &&
2405 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2406 return ConvTy;
2407
2408 // ID acts sort of like void* for ObjC interfaces
2409 if (LHSIface && Context.isObjCIdType(rhptee))
2410 return ConvTy;
2411 if (RHSIface && Context.isObjCIdType(lhptee))
2412 return ConvTy;
2413
Chris Lattner4b009652007-07-25 00:24:17 +00002414 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2415 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002416 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2417 rhptee.getUnqualifiedType()))
2418 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002419 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002420}
2421
Steve Naroff3454b6c2008-09-04 15:10:53 +00002422/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2423/// block pointer types are compatible or whether a block and normal pointer
2424/// are compatible. It is more restrict than comparing two function pointer
2425// types.
2426Sema::AssignConvertType
2427Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2428 QualType rhsType) {
2429 QualType lhptee, rhptee;
2430
2431 // get the "pointed to" type (ignoring qualifiers at the top level)
2432 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2433 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2434
2435 // make sure we operate on the canonical type
2436 lhptee = Context.getCanonicalType(lhptee);
2437 rhptee = Context.getCanonicalType(rhptee);
2438
2439 AssignConvertType ConvTy = Compatible;
2440
2441 // For blocks we enforce that qualifiers are identical.
2442 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2443 ConvTy = CompatiblePointerDiscardsQualifiers;
2444
2445 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2446 return IncompatibleBlockPointer;
2447 return ConvTy;
2448}
2449
Chris Lattner4b009652007-07-25 00:24:17 +00002450/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2451/// has code to accommodate several GCC extensions when type checking
2452/// pointers. Here are some objectionable examples that GCC considers warnings:
2453///
2454/// int a, *pint;
2455/// short *pshort;
2456/// struct foo *pfoo;
2457///
2458/// pint = pshort; // warning: assignment from incompatible pointer type
2459/// a = pint; // warning: assignment makes integer from pointer without a cast
2460/// pint = a; // warning: assignment makes pointer from integer without a cast
2461/// pint = pfoo; // warning: assignment from incompatible pointer type
2462///
2463/// As a result, the code for dealing with pointers is more complex than the
2464/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002465///
Chris Lattner005ed752008-01-04 18:04:52 +00002466Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002467Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002468 // Get canonical types. We're not formatting these types, just comparing
2469 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002470 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2471 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002472
2473 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002474 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002475
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002476 // If the left-hand side is a reference type, then we are in a
2477 // (rare!) case where we've allowed the use of references in C,
2478 // e.g., as a parameter type in a built-in function. In this case,
2479 // just make sure that the type referenced is compatible with the
2480 // right-hand side type. The caller is responsible for adjusting
2481 // lhsType so that the resulting expression does not have reference
2482 // type.
2483 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2484 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002485 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002486 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002487 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002488
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002489 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2490 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002491 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002492 // Relax integer conversions like we do for pointers below.
2493 if (rhsType->isIntegerType())
2494 return IntToPointer;
2495 if (lhsType->isIntegerType())
2496 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002497 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002498 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002499
Nate Begemanc5f0f652008-07-14 18:02:46 +00002500 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002501 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002502 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2503 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002504 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002505
Nate Begemanc5f0f652008-07-14 18:02:46 +00002506 // If we are allowing lax vector conversions, and LHS and RHS are both
2507 // vectors, the total size only needs to be the same. This is a bitcast;
2508 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002509 if (getLangOptions().LaxVectorConversions &&
2510 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002511 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002512 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002513 }
2514 return Incompatible;
2515 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002516
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002517 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002518 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002519
Chris Lattner390564e2008-04-07 06:49:41 +00002520 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002521 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002522 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002523
Chris Lattner390564e2008-04-07 06:49:41 +00002524 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002525 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002526
Steve Naroffa982c712008-09-29 18:10:17 +00002527 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002528 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002529 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002530
2531 // Treat block pointers as objects.
2532 if (getLangOptions().ObjC1 &&
2533 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2534 return Compatible;
2535 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002536 return Incompatible;
2537 }
2538
2539 if (isa<BlockPointerType>(lhsType)) {
2540 if (rhsType->isIntegerType())
2541 return IntToPointer;
2542
Steve Naroffa982c712008-09-29 18:10:17 +00002543 // Treat block pointers as objects.
2544 if (getLangOptions().ObjC1 &&
2545 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2546 return Compatible;
2547
Steve Naroff3454b6c2008-09-04 15:10:53 +00002548 if (rhsType->isBlockPointerType())
2549 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2550
2551 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2552 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002553 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002554 }
Chris Lattner1853da22008-01-04 23:18:45 +00002555 return Incompatible;
2556 }
2557
Chris Lattner390564e2008-04-07 06:49:41 +00002558 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002559 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002560 if (lhsType == Context.BoolTy)
2561 return Compatible;
2562
2563 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002564 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002565
Chris Lattner390564e2008-04-07 06:49:41 +00002566 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002567 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002568
2569 if (isa<BlockPointerType>(lhsType) &&
2570 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002571 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002572 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002573 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002574
Chris Lattner1853da22008-01-04 23:18:45 +00002575 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002576 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002577 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002578 }
2579 return Incompatible;
2580}
2581
Chris Lattner005ed752008-01-04 18:04:52 +00002582Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002583Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002584 if (getLangOptions().CPlusPlus) {
2585 if (!lhsType->isRecordType()) {
2586 // C++ 5.17p3: If the left operand is not of class type, the
2587 // expression is implicitly converted (C++ 4) to the
2588 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002589 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2590 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002591 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002592 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002593 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002594 }
2595
2596 // FIXME: Currently, we fall through and treat C++ classes like C
2597 // structures.
2598 }
2599
Steve Naroffcdee22d2007-11-27 17:58:44 +00002600 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2601 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002602 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2603 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002604 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002605 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002606 return Compatible;
2607 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002608
2609 // We don't allow conversion of non-null-pointer constants to integers.
2610 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2611 return IntToBlockPointer;
2612
Chris Lattner5f505bf2007-10-16 02:55:40 +00002613 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002614 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002615 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002616 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002617 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002618 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002619 if (!lhsType->isReferenceType())
2620 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002621
Chris Lattner005ed752008-01-04 18:04:52 +00002622 Sema::AssignConvertType result =
2623 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002624
2625 // C99 6.5.16.1p2: The value of the right operand is converted to the
2626 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002627 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2628 // so that we can use references in built-in functions even in C.
2629 // The getNonReferenceType() call makes sure that the resulting expression
2630 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002631 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002632 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002633 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002634}
2635
Chris Lattner005ed752008-01-04 18:04:52 +00002636Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002637Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2638 return CheckAssignmentConstraints(lhsType, rhsType);
2639}
2640
Chris Lattner1eafdea2008-11-18 01:30:42 +00002641QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002642 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002643 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002644 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002645 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002646}
2647
Chris Lattner1eafdea2008-11-18 01:30:42 +00002648inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002649 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002650 // For conversion purposes, we ignore any qualifiers.
2651 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002652 QualType lhsType =
2653 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2654 QualType rhsType =
2655 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002656
Nate Begemanc5f0f652008-07-14 18:02:46 +00002657 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002658 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002659 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002660
Nate Begemanc5f0f652008-07-14 18:02:46 +00002661 // Handle the case of a vector & extvector type of the same size and element
2662 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002663 if (getLangOptions().LaxVectorConversions) {
2664 // FIXME: Should we warn here?
2665 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002666 if (const VectorType *RV = rhsType->getAsVectorType())
2667 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002668 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002669 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002670 }
2671 }
2672 }
2673
Nate Begemanc5f0f652008-07-14 18:02:46 +00002674 // If the lhs is an extended vector and the rhs is a scalar of the same type
2675 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002676 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002677 QualType eltType = V->getElementType();
2678
2679 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2680 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2681 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002682 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002683 return lhsType;
2684 }
2685 }
2686
Nate Begemanc5f0f652008-07-14 18:02:46 +00002687 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002688 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002689 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002690 QualType eltType = V->getElementType();
2691
2692 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2693 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2694 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002695 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002696 return rhsType;
2697 }
2698 }
2699
Chris Lattner4b009652007-07-25 00:24:17 +00002700 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002701 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002702 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002703 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002704 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002705}
2706
2707inline QualType Sema::CheckPointerToMemberOperands(
2708 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
2709{
2710 const char *OpSpelling = isIndirect ? "->*" : ".*";
2711 // C++ 5.5p2
2712 // The binary operator .* [p3: ->*] binds its second operand, which shall
2713 // be of type "pointer to member of T" (where T is a completely-defined
2714 // class type) [...]
2715 QualType RType = rex->getType();
2716 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
2717 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) {
2718 Diag(Loc, diag::err_bad_memptr_rhs)
2719 << OpSpelling << RType << rex->getSourceRange();
2720 return QualType();
2721 }
2722 QualType Class(MemPtr->getClass(), 0);
2723
2724 // C++ 5.5p2
2725 // [...] to its first operand, which shall be of class T or of a class of
2726 // which T is an unambiguous and accessible base class. [p3: a pointer to
2727 // such a class]
2728 QualType LType = lex->getType();
2729 if (isIndirect) {
2730 if (const PointerType *Ptr = LType->getAsPointerType())
2731 LType = Ptr->getPointeeType().getNonReferenceType();
2732 else {
2733 Diag(Loc, diag::err_bad_memptr_lhs)
Sebastian Redl34e58bd2009-02-07 00:41:42 +00002734 << OpSpelling << 1 << LType << lex->getSourceRange();
Sebastian Redl95216a62009-02-07 00:15:38 +00002735 return QualType();
2736 }
2737 }
2738
2739 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
2740 Context.getCanonicalType(LType).getUnqualifiedType()) {
2741 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
2742 /*DetectVirtual=*/false);
2743 // FIXME: Would it be useful to print full ambiguity paths,
2744 // or is that overkill?
2745 if (!IsDerivedFrom(LType, Class, Paths) ||
2746 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Sebastian Redl34e58bd2009-02-07 00:41:42 +00002747 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Sebastian Redl95216a62009-02-07 00:15:38 +00002748 << (int)isIndirect << lex->getType() << lex->getSourceRange();
2749 return QualType();
2750 }
2751 }
2752
2753 // C++ 5.5p2
2754 // The result is an object or a function of the type specified by the
2755 // second operand.
2756 // The cv qualifiers are the union of those in the pointer and the left side,
2757 // in accordance with 5.5p5 and 5.2.5.
2758 // FIXME: This returns a dereferenced member function pointer as a normal
2759 // function type. However, the only operation valid on such functions is
2760 // calling them. There's also a GCC extension to get a function pointer to
2761 // the thing, which is another complication, because this type - unlike the
2762 // type that is the result of this expression - takes the class as the first
2763 // argument.
2764 // We probably need a "MemberFunctionClosureType" or something like that.
2765 QualType Result = MemPtr->getPointeeType();
2766 if (LType.isConstQualified())
2767 Result.addConst();
2768 if (LType.isVolatileQualified())
2769 Result.addVolatile();
2770 return Result;
2771}
Chris Lattner4b009652007-07-25 00:24:17 +00002772
2773inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002774 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002775{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002776 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002777 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002778
Steve Naroff8f708362007-08-24 19:07:16 +00002779 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002780
Chris Lattner4b009652007-07-25 00:24:17 +00002781 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002782 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002783 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002784}
2785
2786inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002787 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002788{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002789 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2790 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2791 return CheckVectorOperands(Loc, lex, rex);
2792 return InvalidOperands(Loc, lex, rex);
2793 }
Chris Lattner4b009652007-07-25 00:24:17 +00002794
Steve Naroff8f708362007-08-24 19:07:16 +00002795 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002796
Chris Lattner4b009652007-07-25 00:24:17 +00002797 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002798 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002799 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002800}
2801
2802inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002803 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002804{
2805 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002806 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002807
Steve Naroff8f708362007-08-24 19:07:16 +00002808 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002809
Chris Lattner4b009652007-07-25 00:24:17 +00002810 // handle the common case first (both operands are arithmetic).
2811 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002812 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002813
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002814 // Put any potential pointer into PExp
2815 Expr* PExp = lex, *IExp = rex;
2816 if (IExp->getType()->isPointerType())
2817 std::swap(PExp, IExp);
2818
2819 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2820 if (IExp->getType()->isIntegerType()) {
2821 // Check for arithmetic on pointers to incomplete types
2822 if (!PTy->getPointeeType()->isObjectType()) {
2823 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002824 if (getLangOptions().CPlusPlus) {
2825 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2826 << lex->getSourceRange() << rex->getSourceRange();
2827 return QualType();
2828 }
2829
2830 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002831 Diag(Loc, diag::ext_gnu_void_ptr)
2832 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002833 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002834 if (getLangOptions().CPlusPlus) {
2835 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2836 << lex->getType() << lex->getSourceRange();
2837 return QualType();
2838 }
2839
2840 // GNU extension: arithmetic on pointer to function
2841 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002842 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002843 } else {
2844 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2845 diag::err_typecheck_arithmetic_incomplete_type,
2846 lex->getSourceRange(), SourceRange(),
2847 lex->getType());
2848 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002849 }
2850 }
2851 return PExp->getType();
2852 }
2853 }
2854
Chris Lattner1eafdea2008-11-18 01:30:42 +00002855 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002856}
2857
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002858// C99 6.5.6
2859QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002860 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002861 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002862 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002863
Steve Naroff8f708362007-08-24 19:07:16 +00002864 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002865
Chris Lattnerf6da2912007-12-09 21:53:25 +00002866 // Enforce type constraints: C99 6.5.6p3.
2867
2868 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002869 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002870 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002871
2872 // Either ptr - int or ptr - ptr.
2873 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002874 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002875
Chris Lattnerf6da2912007-12-09 21:53:25 +00002876 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002877 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002878 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002879 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002880 Diag(Loc, diag::ext_gnu_void_ptr)
2881 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002882 } else if (lpointee->isFunctionType()) {
2883 if (getLangOptions().CPlusPlus) {
2884 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2885 << lex->getType() << lex->getSourceRange();
2886 return QualType();
2887 }
2888
2889 // GNU extension: arithmetic on pointer to function
2890 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2891 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002892 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002893 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002894 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002895 return QualType();
2896 }
2897 }
2898
2899 // The result type of a pointer-int computation is the pointer type.
2900 if (rex->getType()->isIntegerType())
2901 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002902
Chris Lattnerf6da2912007-12-09 21:53:25 +00002903 // Handle pointer-pointer subtractions.
2904 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002905 QualType rpointee = RHSPTy->getPointeeType();
2906
Chris Lattnerf6da2912007-12-09 21:53:25 +00002907 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002908 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002909 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002910 if (rpointee->isVoidType()) {
2911 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002912 Diag(Loc, diag::ext_gnu_void_ptr)
2913 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002914 } else if (rpointee->isFunctionType()) {
2915 if (getLangOptions().CPlusPlus) {
2916 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2917 << rex->getType() << rex->getSourceRange();
2918 return QualType();
2919 }
2920
2921 // GNU extension: arithmetic on pointer to function
2922 if (!lpointee->isFunctionType())
2923 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2924 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002925 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002926 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002927 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002928 return QualType();
2929 }
2930 }
2931
2932 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002933 if (!Context.typesAreCompatible(
2934 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2935 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002936 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002937 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002938 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002939 return QualType();
2940 }
2941
2942 return Context.getPointerDiffType();
2943 }
2944 }
2945
Chris Lattner1eafdea2008-11-18 01:30:42 +00002946 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002947}
2948
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002949// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002950QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002951 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002952 // C99 6.5.7p2: Each of the operands shall have integer type.
2953 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002954 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002955
Chris Lattner2c8bff72007-12-12 05:47:28 +00002956 // Shifts don't perform usual arithmetic conversions, they just do integer
2957 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002958 if (!isCompAssign)
2959 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002960 UsualUnaryConversions(rex);
2961
2962 // "The type of the result is that of the promoted left operand."
2963 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002964}
2965
Eli Friedman0d9549b2008-08-22 00:56:42 +00002966static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2967 ASTContext& Context) {
2968 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2969 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2970 // ID acts sort of like void* for ObjC interfaces
2971 if (LHSIface && Context.isObjCIdType(RHS))
2972 return true;
2973 if (RHSIface && Context.isObjCIdType(LHS))
2974 return true;
2975 if (!LHSIface || !RHSIface)
2976 return false;
2977 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2978 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2979}
2980
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002981// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002982QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002983 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002984 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002985 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002986
Chris Lattner254f3bc2007-08-26 01:18:55 +00002987 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002988 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2989 UsualArithmeticConversions(lex, rex);
2990 else {
2991 UsualUnaryConversions(lex);
2992 UsualUnaryConversions(rex);
2993 }
Chris Lattner4b009652007-07-25 00:24:17 +00002994 QualType lType = lex->getType();
2995 QualType rType = rex->getType();
2996
Ted Kremenek486509e2007-10-29 17:13:39 +00002997 // For non-floating point types, check for self-comparisons of the form
2998 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2999 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003000 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003001 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3002 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003003 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003004 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003005 }
3006
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003007 // The result of comparisons is 'bool' in C++, 'int' in C.
3008 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3009
Chris Lattner254f3bc2007-08-26 01:18:55 +00003010 if (isRelational) {
3011 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003012 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003013 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003014 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003015 if (lType->isFloatingType()) {
3016 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003017 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003018 }
3019
Chris Lattner254f3bc2007-08-26 01:18:55 +00003020 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003021 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003022 }
Chris Lattner4b009652007-07-25 00:24:17 +00003023
Chris Lattner22be8422007-08-26 01:10:14 +00003024 bool LHSIsNull = lex->isNullPointerConstant(Context);
3025 bool RHSIsNull = rex->isNullPointerConstant(Context);
3026
Chris Lattner254f3bc2007-08-26 01:18:55 +00003027 // All of the following pointer related warnings are GCC extensions, except
3028 // when handling null pointer constants. One day, we can consider making them
3029 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003030 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003031 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003032 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003033 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003034 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003035
Steve Naroff3b435622007-11-13 14:57:38 +00003036 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003037 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3038 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003039 RCanPointeeTy.getUnqualifiedType()) &&
3040 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003041 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003042 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003043 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003044 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003045 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003046 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003047 // Handle block pointer types.
3048 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3049 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3050 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3051
3052 if (!LHSIsNull && !RHSIsNull &&
3053 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003054 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003055 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003056 }
3057 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003058 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003059 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003060 // Allow block pointers to be compared with null pointer constants.
3061 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3062 (lType->isPointerType() && rType->isBlockPointerType())) {
3063 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003064 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003065 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003066 }
3067 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003068 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003069 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003070
Steve Naroff936c4362008-06-03 14:04:54 +00003071 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003072 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003073 const PointerType *LPT = lType->getAsPointerType();
3074 const PointerType *RPT = rType->getAsPointerType();
3075 bool LPtrToVoid = LPT ?
3076 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3077 bool RPtrToVoid = RPT ?
3078 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3079
3080 if (!LPtrToVoid && !RPtrToVoid &&
3081 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003082 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003083 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003084 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003085 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003086 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003087 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003088 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003089 }
Steve Naroff936c4362008-06-03 14:04:54 +00003090 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3091 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003092 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003093 } else {
3094 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003095 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003096 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003097 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003098 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003099 }
Steve Naroff936c4362008-06-03 14:04:54 +00003100 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003101 }
Steve Naroff936c4362008-06-03 14:04:54 +00003102 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3103 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003104 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003105 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003106 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003107 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003108 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003109 }
Steve Naroff936c4362008-06-03 14:04:54 +00003110 if (lType->isIntegerType() &&
3111 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003112 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003113 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003114 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003115 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003116 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003117 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003118 // Handle block pointers.
3119 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3120 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003121 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003122 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003123 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003124 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003125 }
3126 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3127 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003128 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003129 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003130 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003131 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003132 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003133 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003134}
3135
Nate Begemanc5f0f652008-07-14 18:02:46 +00003136/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3137/// operates on extended vector types. Instead of producing an IntTy result,
3138/// like a scalar comparison, a vector comparison produces a vector of integer
3139/// types.
3140QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003141 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003142 bool isRelational) {
3143 // Check to make sure we're operating on vectors of the same type and width,
3144 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003145 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003146 if (vType.isNull())
3147 return vType;
3148
3149 QualType lType = lex->getType();
3150 QualType rType = rex->getType();
3151
3152 // For non-floating point types, check for self-comparisons of the form
3153 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3154 // often indicate logic errors in the program.
3155 if (!lType->isFloatingType()) {
3156 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3157 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3158 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003159 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003160 }
3161
3162 // Check for comparisons of floating point operands using != and ==.
3163 if (!isRelational && lType->isFloatingType()) {
3164 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003165 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003166 }
3167
3168 // Return the type for the comparison, which is the same as vector type for
3169 // integer vectors, or an integer type of identical size and number of
3170 // elements for floating point vectors.
3171 if (lType->isIntegerType())
3172 return lType;
3173
3174 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003175 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003176 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003177 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003178 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3179 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3180
3181 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3182 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003183 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3184}
3185
Chris Lattner4b009652007-07-25 00:24:17 +00003186inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003187 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003188{
3189 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003190 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003191
Steve Naroff8f708362007-08-24 19:07:16 +00003192 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003193
3194 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003195 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003196 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003197}
3198
3199inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003200 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003201{
3202 UsualUnaryConversions(lex);
3203 UsualUnaryConversions(rex);
3204
Eli Friedmanbea3f842008-05-13 20:16:47 +00003205 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003206 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003207 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003208}
3209
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003210/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3211/// is a read-only property; return true if so. A readonly property expression
3212/// depends on various declarations and thus must be treated specially.
3213///
3214static bool IsReadonlyProperty(Expr *E, Sema &S)
3215{
3216 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3217 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3218 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3219 QualType BaseType = PropExpr->getBase()->getType();
3220 if (const PointerType *PTy = BaseType->getAsPointerType())
3221 if (const ObjCInterfaceType *IFTy =
3222 PTy->getPointeeType()->getAsObjCInterfaceType())
3223 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3224 if (S.isPropertyReadonly(PDecl, IFace))
3225 return true;
3226 }
3227 }
3228 return false;
3229}
3230
Chris Lattner4c2642c2008-11-18 01:22:49 +00003231/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3232/// emit an error and return true. If so, return false.
3233static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003234 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3235 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3236 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003237 if (IsLV == Expr::MLV_Valid)
3238 return false;
3239
3240 unsigned Diag = 0;
3241 bool NeedType = false;
3242 switch (IsLV) { // C99 6.5.16p2
3243 default: assert(0 && "Unknown result from isModifiableLvalue!");
3244 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003245 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003246 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3247 NeedType = true;
3248 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003249 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003250 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3251 NeedType = true;
3252 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003253 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003254 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3255 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003256 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003257 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3258 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003259 case Expr::MLV_IncompleteType:
3260 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003261 return S.DiagnoseIncompleteType(Loc, E->getType(),
3262 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3263 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003264 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003265 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3266 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003267 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003268 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3269 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003270 case Expr::MLV_ReadonlyProperty:
3271 Diag = diag::error_readonly_property_assignment;
3272 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003273 case Expr::MLV_NoSetterProperty:
3274 Diag = diag::error_nosetter_property_assignment;
3275 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003276 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003277
Chris Lattner4c2642c2008-11-18 01:22:49 +00003278 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003279 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003280 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003281 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003282 return true;
3283}
3284
3285
3286
3287// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003288QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3289 SourceLocation Loc,
3290 QualType CompoundType) {
3291 // Verify that LHS is a modifiable lvalue, and emit error if not.
3292 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003293 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003294
3295 QualType LHSType = LHS->getType();
3296 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003297
Chris Lattner005ed752008-01-04 18:04:52 +00003298 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003299 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003300 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003301 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003302 // Special case of NSObject attributes on c-style pointer types.
3303 if (ConvTy == IncompatiblePointer &&
3304 ((Context.isObjCNSObjectType(LHSType) &&
3305 Context.isObjCObjectPointerType(RHSType)) ||
3306 (Context.isObjCNSObjectType(RHSType) &&
3307 Context.isObjCObjectPointerType(LHSType))))
3308 ConvTy = Compatible;
3309
Chris Lattner34c85082008-08-21 18:04:13 +00003310 // If the RHS is a unary plus or minus, check to see if they = and + are
3311 // right next to each other. If so, the user may have typo'd "x =+ 4"
3312 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003313 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003314 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3315 RHSCheck = ICE->getSubExpr();
3316 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3317 if ((UO->getOpcode() == UnaryOperator::Plus ||
3318 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003319 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003320 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003321 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003322 Diag(Loc, diag::warn_not_compound_assign)
3323 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3324 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003325 }
3326 } else {
3327 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003328 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003329 }
Chris Lattner005ed752008-01-04 18:04:52 +00003330
Chris Lattner1eafdea2008-11-18 01:30:42 +00003331 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3332 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003333 return QualType();
3334
Chris Lattner4b009652007-07-25 00:24:17 +00003335 // C99 6.5.16p3: The type of an assignment expression is the type of the
3336 // left operand unless the left operand has qualified type, in which case
3337 // it is the unqualified version of the type of the left operand.
3338 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3339 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003340 // C++ 5.17p1: the type of the assignment expression is that of its left
3341 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003342 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003343}
3344
Chris Lattner1eafdea2008-11-18 01:30:42 +00003345// C99 6.5.17
3346QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3347 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003348
3349 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003350 DefaultFunctionArrayConversion(RHS);
3351 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003352}
3353
3354/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3355/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003356QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3357 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003358 QualType ResType = Op->getType();
3359 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003360
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003361 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3362 // Decrement of bool is not allowed.
3363 if (!isInc) {
3364 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3365 return QualType();
3366 }
3367 // Increment of bool sets it to true, but is deprecated.
3368 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3369 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003370 // OK!
3371 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3372 // C99 6.5.2.4p2, 6.5.6p2
3373 if (PT->getPointeeType()->isObjectType()) {
3374 // Pointer to object is ok!
3375 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003376 if (getLangOptions().CPlusPlus) {
3377 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3378 << Op->getSourceRange();
3379 return QualType();
3380 }
3381
3382 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003383 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003384 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003385 if (getLangOptions().CPlusPlus) {
3386 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3387 << Op->getType() << Op->getSourceRange();
3388 return QualType();
3389 }
3390
3391 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003392 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003393 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003394 } else {
3395 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3396 diag::err_typecheck_arithmetic_incomplete_type,
3397 Op->getSourceRange(), SourceRange(),
3398 ResType);
3399 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003400 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003401 } else if (ResType->isComplexType()) {
3402 // C99 does not support ++/-- on complex types, we allow as an extension.
3403 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003404 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003405 } else {
3406 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003407 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003408 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003409 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003410 // At this point, we know we have a real, complex or pointer type.
3411 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003412 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003413 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003414 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003415}
3416
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003417/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003418/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003419/// where the declaration is needed for type checking. We only need to
3420/// handle cases when the expression references a function designator
3421/// or is an lvalue. Here are some examples:
3422/// - &(x) => x
3423/// - &*****f => f for f a function designator.
3424/// - &s.xx => s
3425/// - &s.zz[1].yy -> s, if zz is an array
3426/// - *(x + 1) -> x, if x is an array
3427/// - &"123"[2] -> 0
3428/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003429static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003430 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003431 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003432 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003433 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003434 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003435 // Fields cannot be declared with a 'register' storage class.
3436 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003437 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003438 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003439 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003440 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003441 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003442
Douglas Gregord2baafd2008-10-21 16:13:35 +00003443 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003444 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003445 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003446 return 0;
3447 else
3448 return VD;
3449 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003450 case Stmt::UnaryOperatorClass: {
3451 UnaryOperator *UO = cast<UnaryOperator>(E);
3452
3453 switch(UO->getOpcode()) {
3454 case UnaryOperator::Deref: {
3455 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003456 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3457 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3458 if (!VD || VD->getType()->isPointerType())
3459 return 0;
3460 return VD;
3461 }
3462 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003463 }
3464 case UnaryOperator::Real:
3465 case UnaryOperator::Imag:
3466 case UnaryOperator::Extension:
3467 return getPrimaryDecl(UO->getSubExpr());
3468 default:
3469 return 0;
3470 }
3471 }
3472 case Stmt::BinaryOperatorClass: {
3473 BinaryOperator *BO = cast<BinaryOperator>(E);
3474
3475 // Handle cases involving pointer arithmetic. The result of an
3476 // Assign or AddAssign is not an lvalue so they can be ignored.
3477
3478 // (x + n) or (n + x) => x
3479 if (BO->getOpcode() == BinaryOperator::Add) {
3480 if (BO->getLHS()->getType()->isPointerType()) {
3481 return getPrimaryDecl(BO->getLHS());
3482 } else if (BO->getRHS()->getType()->isPointerType()) {
3483 return getPrimaryDecl(BO->getRHS());
3484 }
3485 }
3486
3487 return 0;
3488 }
Chris Lattner4b009652007-07-25 00:24:17 +00003489 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003490 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003491 case Stmt::ImplicitCastExprClass:
3492 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003493 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003494 default:
3495 return 0;
3496 }
3497}
3498
3499/// CheckAddressOfOperand - The operand of & must be either a function
3500/// designator or an lvalue designating an object. If it is an lvalue, the
3501/// object cannot be declared with storage class register or be a bit field.
3502/// Note: The usual conversions are *not* applied to the operand of the &
3503/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003504/// In C++, the operand might be an overloaded function name, in which case
3505/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003506QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003507 if (op->isTypeDependent())
3508 return Context.DependentTy;
3509
Steve Naroff9c6c3592008-01-13 17:10:08 +00003510 if (getLangOptions().C99) {
3511 // Implement C99-only parts of addressof rules.
3512 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3513 if (uOp->getOpcode() == UnaryOperator::Deref)
3514 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3515 // (assuming the deref expression is valid).
3516 return uOp->getSubExpr()->getType();
3517 }
3518 // Technically, there should be a check for array subscript
3519 // expressions here, but the result of one is always an lvalue anyway.
3520 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003521 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003522 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003523
Chris Lattner4b009652007-07-25 00:24:17 +00003524 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003525 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3526 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003527 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3528 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003529 return QualType();
3530 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003531 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003532 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3533 if (Field->isBitField()) {
3534 Diag(OpLoc, diag::err_typecheck_address_of)
3535 << "bit-field" << op->getSourceRange();
3536 return QualType();
3537 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003538 }
3539 // Check for Apple extension for accessing vector components.
3540 } else if (isa<ArraySubscriptExpr>(op) &&
3541 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003542 Diag(OpLoc, diag::err_typecheck_address_of)
3543 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003544 return QualType();
3545 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003546 // We have an lvalue with a decl. Make sure the decl is not declared
3547 // with the register storage-class specifier.
3548 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3549 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003550 Diag(OpLoc, diag::err_typecheck_address_of)
3551 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003552 return QualType();
3553 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003554 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003555 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003556 } else if (isa<FieldDecl>(dcl)) {
3557 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003558 // Could be a pointer to member, though, if there is an explicit
3559 // scope qualifier for the class.
3560 if (isa<QualifiedDeclRefExpr>(op)) {
3561 DeclContext *Ctx = dcl->getDeclContext();
3562 if (Ctx && Ctx->isRecord())
3563 return Context.getMemberPointerType(op->getType(),
3564 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3565 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003566 } else if (isa<FunctionDecl>(dcl)) {
3567 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003568 // As above.
3569 if (isa<QualifiedDeclRefExpr>(op)) {
3570 DeclContext *Ctx = dcl->getDeclContext();
3571 if (Ctx && Ctx->isRecord())
3572 return Context.getMemberPointerType(op->getType(),
3573 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3574 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003575 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003576 else
Chris Lattner4b009652007-07-25 00:24:17 +00003577 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003578 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003579
Chris Lattner4b009652007-07-25 00:24:17 +00003580 // If the operand has type "type", the result has type "pointer to type".
3581 return Context.getPointerType(op->getType());
3582}
3583
Chris Lattnerda5c0872008-11-23 09:13:29 +00003584QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3585 UsualUnaryConversions(Op);
3586 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003587
Chris Lattnerda5c0872008-11-23 09:13:29 +00003588 // Note that per both C89 and C99, this is always legal, even if ptype is an
3589 // incomplete type or void. It would be possible to warn about dereferencing
3590 // a void pointer, but it's completely well-defined, and such a warning is
3591 // unlikely to catch any mistakes.
3592 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003593 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003594
Chris Lattner77d52da2008-11-20 06:06:08 +00003595 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003596 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003597 return QualType();
3598}
3599
3600static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3601 tok::TokenKind Kind) {
3602 BinaryOperator::Opcode Opc;
3603 switch (Kind) {
3604 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003605 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3606 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003607 case tok::star: Opc = BinaryOperator::Mul; break;
3608 case tok::slash: Opc = BinaryOperator::Div; break;
3609 case tok::percent: Opc = BinaryOperator::Rem; break;
3610 case tok::plus: Opc = BinaryOperator::Add; break;
3611 case tok::minus: Opc = BinaryOperator::Sub; break;
3612 case tok::lessless: Opc = BinaryOperator::Shl; break;
3613 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3614 case tok::lessequal: Opc = BinaryOperator::LE; break;
3615 case tok::less: Opc = BinaryOperator::LT; break;
3616 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3617 case tok::greater: Opc = BinaryOperator::GT; break;
3618 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3619 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3620 case tok::amp: Opc = BinaryOperator::And; break;
3621 case tok::caret: Opc = BinaryOperator::Xor; break;
3622 case tok::pipe: Opc = BinaryOperator::Or; break;
3623 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3624 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3625 case tok::equal: Opc = BinaryOperator::Assign; break;
3626 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3627 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3628 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3629 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3630 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3631 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3632 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3633 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3634 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3635 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3636 case tok::comma: Opc = BinaryOperator::Comma; break;
3637 }
3638 return Opc;
3639}
3640
3641static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3642 tok::TokenKind Kind) {
3643 UnaryOperator::Opcode Opc;
3644 switch (Kind) {
3645 default: assert(0 && "Unknown unary op!");
3646 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3647 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3648 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3649 case tok::star: Opc = UnaryOperator::Deref; break;
3650 case tok::plus: Opc = UnaryOperator::Plus; break;
3651 case tok::minus: Opc = UnaryOperator::Minus; break;
3652 case tok::tilde: Opc = UnaryOperator::Not; break;
3653 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003654 case tok::kw___real: Opc = UnaryOperator::Real; break;
3655 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3656 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3657 }
3658 return Opc;
3659}
3660
Douglas Gregord7f915e2008-11-06 23:29:22 +00003661/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3662/// operator @p Opc at location @c TokLoc. This routine only supports
3663/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003664Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3665 unsigned Op,
3666 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003667 QualType ResultTy; // Result type of the binary operator.
3668 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3669 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3670
3671 switch (Opc) {
3672 default:
3673 assert(0 && "Unknown binary expr!");
3674 case BinaryOperator::Assign:
3675 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3676 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003677 case BinaryOperator::PtrMemD:
3678 case BinaryOperator::PtrMemI:
3679 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3680 Opc == BinaryOperator::PtrMemI);
3681 break;
3682 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003683 case BinaryOperator::Div:
3684 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3685 break;
3686 case BinaryOperator::Rem:
3687 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3688 break;
3689 case BinaryOperator::Add:
3690 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3691 break;
3692 case BinaryOperator::Sub:
3693 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3694 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003695 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003696 case BinaryOperator::Shr:
3697 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3698 break;
3699 case BinaryOperator::LE:
3700 case BinaryOperator::LT:
3701 case BinaryOperator::GE:
3702 case BinaryOperator::GT:
3703 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3704 break;
3705 case BinaryOperator::EQ:
3706 case BinaryOperator::NE:
3707 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3708 break;
3709 case BinaryOperator::And:
3710 case BinaryOperator::Xor:
3711 case BinaryOperator::Or:
3712 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3713 break;
3714 case BinaryOperator::LAnd:
3715 case BinaryOperator::LOr:
3716 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3717 break;
3718 case BinaryOperator::MulAssign:
3719 case BinaryOperator::DivAssign:
3720 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3721 if (!CompTy.isNull())
3722 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3723 break;
3724 case BinaryOperator::RemAssign:
3725 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3726 if (!CompTy.isNull())
3727 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3728 break;
3729 case BinaryOperator::AddAssign:
3730 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3731 if (!CompTy.isNull())
3732 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3733 break;
3734 case BinaryOperator::SubAssign:
3735 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3736 if (!CompTy.isNull())
3737 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3738 break;
3739 case BinaryOperator::ShlAssign:
3740 case BinaryOperator::ShrAssign:
3741 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3742 if (!CompTy.isNull())
3743 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3744 break;
3745 case BinaryOperator::AndAssign:
3746 case BinaryOperator::XorAssign:
3747 case BinaryOperator::OrAssign:
3748 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3749 if (!CompTy.isNull())
3750 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3751 break;
3752 case BinaryOperator::Comma:
3753 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3754 break;
3755 }
3756 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003757 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003758 if (CompTy.isNull())
3759 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3760 else
3761 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003762 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003763}
3764
Chris Lattner4b009652007-07-25 00:24:17 +00003765// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003766Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3767 tok::TokenKind Kind,
3768 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003769 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003770 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003771
Steve Naroff87d58b42007-09-16 03:34:24 +00003772 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3773 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003774
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003775 // If either expression is type-dependent, just build the AST.
3776 // FIXME: We'll need to perform some caching of the result of name
3777 // lookup for operator+.
3778 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003779 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3780 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003781 Context.DependentTy,
3782 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003783 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003784 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3785 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003786 }
3787
Sebastian Redl95216a62009-02-07 00:15:38 +00003788 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003789 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3790 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003791 // If this is one of the assignment operators, we only perform
3792 // overload resolution if the left-hand side is a class or
3793 // enumeration type (C++ [expr.ass]p3).
3794 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3795 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3796 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3797 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003798
Douglas Gregord7f915e2008-11-06 23:29:22 +00003799 // Determine which overloaded operator we're dealing with.
3800 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003801 // Overloading .* is not possible.
3802 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003803 OO_Star, OO_Slash, OO_Percent,
3804 OO_Plus, OO_Minus,
3805 OO_LessLess, OO_GreaterGreater,
3806 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3807 OO_EqualEqual, OO_ExclaimEqual,
3808 OO_Amp,
3809 OO_Caret,
3810 OO_Pipe,
3811 OO_AmpAmp,
3812 OO_PipePipe,
3813 OO_Equal, OO_StarEqual,
3814 OO_SlashEqual, OO_PercentEqual,
3815 OO_PlusEqual, OO_MinusEqual,
3816 OO_LessLessEqual, OO_GreaterGreaterEqual,
3817 OO_AmpEqual, OO_CaretEqual,
3818 OO_PipeEqual,
3819 OO_Comma
3820 };
3821 OverloadedOperatorKind OverOp = OverOps[Opc];
3822
Douglas Gregor5ed15042008-11-18 23:14:02 +00003823 // Add the appropriate overloaded operators (C++ [over.match.oper])
3824 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003825 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003826 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003827 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3828 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003829
3830 // Perform overload resolution.
3831 OverloadCandidateSet::iterator Best;
3832 switch (BestViableFunction(CandidateSet, Best)) {
3833 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003834 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003835 FunctionDecl *FnDecl = Best->Function;
3836
Douglas Gregor70d26122008-11-12 17:17:38 +00003837 if (FnDecl) {
3838 // We matched an overloaded operator. Build a call to that
3839 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003840
Douglas Gregor70d26122008-11-12 17:17:38 +00003841 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3843 if (PerformObjectArgumentInitialization(lhs, Method) ||
3844 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3845 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003846 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003847 } else {
3848 // Convert the arguments.
3849 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3850 "passing") ||
3851 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3852 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003853 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003854 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003855
Douglas Gregor70d26122008-11-12 17:17:38 +00003856 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003857 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003858 = FnDecl->getType()->getAsFunctionType()->getResultType();
3859 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003860
Douglas Gregor70d26122008-11-12 17:17:38 +00003861 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003862 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3863 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003864 UsualUnaryConversions(FnExpr);
3865
Steve Naroff774e4152009-01-21 00:14:39 +00003866 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3867 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003868 } else {
3869 // We matched a built-in operator. Convert the arguments, then
3870 // break out so that we will build the appropriate built-in
3871 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003872 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3873 Best->Conversions[0], "passing") ||
3874 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3875 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003876 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003877
3878 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003879 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003880 }
3881
3882 case OR_No_Viable_Function:
3883 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003884 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003885 break;
3886
3887 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003888 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3889 << BinaryOperator::getOpcodeStr(Opc)
3890 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003891 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003892 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003893 }
3894
Douglas Gregor70d26122008-11-12 17:17:38 +00003895 // Either we found no viable overloaded operator or we matched a
3896 // built-in operator. In either case, fall through to trying to
3897 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003898 }
3899
Douglas Gregord7f915e2008-11-06 23:29:22 +00003900 // Build a built-in binary operation.
3901 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003902}
3903
3904// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003905Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3906 tok::TokenKind Op, ExprArg input) {
3907 // FIXME: Input is modified later, but smart pointer not reassigned.
3908 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003909 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003910
3911 if (getLangOptions().CPlusPlus &&
3912 (Input->getType()->isRecordType()
3913 || Input->getType()->isEnumeralType())) {
3914 // Determine which overloaded operator we're dealing with.
3915 static const OverloadedOperatorKind OverOps[] = {
3916 OO_None, OO_None,
3917 OO_PlusPlus, OO_MinusMinus,
3918 OO_Amp, OO_Star,
3919 OO_Plus, OO_Minus,
3920 OO_Tilde, OO_Exclaim,
3921 OO_None, OO_None,
3922 OO_None,
3923 OO_None
3924 };
3925 OverloadedOperatorKind OverOp = OverOps[Opc];
3926
3927 // Add the appropriate overloaded operators (C++ [over.match.oper])
3928 // to the candidate set.
3929 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003930 if (OverOp != OO_None &&
3931 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3932 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003933
3934 // Perform overload resolution.
3935 OverloadCandidateSet::iterator Best;
3936 switch (BestViableFunction(CandidateSet, Best)) {
3937 case OR_Success: {
3938 // We found a built-in operator or an overloaded operator.
3939 FunctionDecl *FnDecl = Best->Function;
3940
3941 if (FnDecl) {
3942 // We matched an overloaded operator. Build a call to that
3943 // operator.
3944
3945 // Convert the arguments.
3946 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3947 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003948 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003949 } else {
3950 // Convert the arguments.
3951 if (PerformCopyInitialization(Input,
3952 FnDecl->getParamDecl(0)->getType(),
3953 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003954 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003955 }
3956
3957 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003958 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003959 = FnDecl->getType()->getAsFunctionType()->getResultType();
3960 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003961
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003962 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003963 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3964 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003965 UsualUnaryConversions(FnExpr);
3966
Sebastian Redl8b769972009-01-19 00:08:26 +00003967 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003968 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3969 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003970 } else {
3971 // We matched a built-in operator. Convert the arguments, then
3972 // break out so that we will build the appropriate built-in
3973 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003974 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3975 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003976 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003977
3978 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003979 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003980 }
3981
3982 case OR_No_Viable_Function:
3983 // No viable function; fall through to handling this as a
3984 // built-in operator, which will produce an error message for us.
3985 break;
3986
3987 case OR_Ambiguous:
3988 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3989 << UnaryOperator::getOpcodeStr(Opc)
3990 << Input->getSourceRange();
3991 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003992 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003993 }
3994
3995 // Either we found no viable overloaded operator or we matched a
3996 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003997 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003998 }
3999
Chris Lattner4b009652007-07-25 00:24:17 +00004000 QualType resultType;
4001 switch (Opc) {
4002 default:
4003 assert(0 && "Unimplemented unary expr!");
4004 case UnaryOperator::PreInc:
4005 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004006 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4007 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004008 break;
4009 case UnaryOperator::AddrOf:
4010 resultType = CheckAddressOfOperand(Input, OpLoc);
4011 break;
4012 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004013 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004014 resultType = CheckIndirectionOperand(Input, OpLoc);
4015 break;
4016 case UnaryOperator::Plus:
4017 case UnaryOperator::Minus:
4018 UsualUnaryConversions(Input);
4019 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004020 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4021 break;
4022 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4023 resultType->isEnumeralType())
4024 break;
4025 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4026 Opc == UnaryOperator::Plus &&
4027 resultType->isPointerType())
4028 break;
4029
Sebastian Redl8b769972009-01-19 00:08:26 +00004030 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4031 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004032 case UnaryOperator::Not: // bitwise complement
4033 UsualUnaryConversions(Input);
4034 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004035 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4036 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4037 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004038 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004039 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004040 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004041 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4042 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004043 break;
4044 case UnaryOperator::LNot: // logical negation
4045 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4046 DefaultFunctionArrayConversion(Input);
4047 resultType = Input->getType();
4048 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004049 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4050 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004051 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004052 // In C++, it's bool. C++ 5.3.1p8
4053 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004054 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004055 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004056 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00004057 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00004058 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004059 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004060 resultType = Input->getType();
4061 break;
4062 }
4063 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004064 return ExprError();
4065 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004066 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004067}
4068
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004069/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4070Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004071 SourceLocation LabLoc,
4072 IdentifierInfo *LabelII) {
4073 // Look up the record for this label identifier.
4074 LabelStmt *&LabelDecl = LabelMap[LabelII];
4075
Daniel Dunbar879788d2008-08-04 16:51:22 +00004076 // If we haven't seen this label yet, create a forward reference. It
4077 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004078 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004079 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004080
4081 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004082 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4083 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004084}
4085
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004086Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004087 SourceLocation RPLoc) { // "({..})"
4088 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4089 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4090 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4091
Eli Friedmanbc941e12009-01-24 23:09:00 +00004092 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4093 if (isFileScope) {
4094 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4095 }
4096
Chris Lattner4b009652007-07-25 00:24:17 +00004097 // FIXME: there are a variety of strange constraints to enforce here, for
4098 // example, it is not possible to goto into a stmt expression apparently.
4099 // More semantic analysis is needed.
4100
4101 // FIXME: the last statement in the compount stmt has its value used. We
4102 // should not warn about it being unused.
4103
4104 // If there are sub stmts in the compound stmt, take the type of the last one
4105 // as the type of the stmtexpr.
4106 QualType Ty = Context.VoidTy;
4107
Chris Lattner200964f2008-07-26 19:51:01 +00004108 if (!Compound->body_empty()) {
4109 Stmt *LastStmt = Compound->body_back();
4110 // If LastStmt is a label, skip down through into the body.
4111 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4112 LastStmt = Label->getSubStmt();
4113
4114 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004115 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004116 }
Chris Lattner4b009652007-07-25 00:24:17 +00004117
Steve Naroff774e4152009-01-21 00:14:39 +00004118 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004119}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004120
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004121Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4122 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004123 SourceLocation TypeLoc,
4124 TypeTy *argty,
4125 OffsetOfComponent *CompPtr,
4126 unsigned NumComponents,
4127 SourceLocation RPLoc) {
4128 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4129 assert(!ArgTy.isNull() && "Missing type argument!");
4130
4131 // We must have at least one component that refers to the type, and the first
4132 // one is known to be a field designator. Verify that the ArgTy represents
4133 // a struct/union/class.
4134 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004135 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004136
4137 // Otherwise, create a compound literal expression as the base, and
4138 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004139 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004140 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004141 IList->setType(ArgTy);
4142 Expr *Res =
4143 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4144
Chris Lattnerb37522e2007-08-31 21:49:13 +00004145 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4146 // GCC extension, diagnose them.
4147 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004148 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4149 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004150
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004151 for (unsigned i = 0; i != NumComponents; ++i) {
4152 const OffsetOfComponent &OC = CompPtr[i];
4153 if (OC.isBrackets) {
4154 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004155 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004156 if (!AT) {
4157 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004158 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004159 }
4160
Chris Lattner2af6a802007-08-30 17:59:59 +00004161 // FIXME: C++: Verify that operator[] isn't overloaded.
4162
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004163 // C99 6.5.2.1p1
4164 Expr *Idx = static_cast<Expr*>(OC.U.E);
4165 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004166 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4167 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004168
Steve Naroff774e4152009-01-21 00:14:39 +00004169 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4170 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004171 continue;
4172 }
4173
4174 const RecordType *RC = Res->getType()->getAsRecordType();
4175 if (!RC) {
4176 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004177 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004178 }
4179
4180 // Get the decl corresponding to this.
4181 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004182 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004183 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4184 LookupMemberName)
4185 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004186 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004187 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4188 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004189
4190 // FIXME: C++: Verify that MemberDecl isn't a static field.
4191 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004192 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4193 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004194 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4195 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004196 }
4197
Steve Naroff774e4152009-01-21 00:14:39 +00004198 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4199 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004200}
4201
4202
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004203Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004204 TypeTy *arg1, TypeTy *arg2,
4205 SourceLocation RPLoc) {
4206 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4207 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4208
4209 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4210
Steve Naroff774e4152009-01-21 00:14:39 +00004211 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4212 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004213}
4214
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004215Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004216 ExprTy *expr1, ExprTy *expr2,
4217 SourceLocation RPLoc) {
4218 Expr *CondExpr = static_cast<Expr*>(cond);
4219 Expr *LHSExpr = static_cast<Expr*>(expr1);
4220 Expr *RHSExpr = static_cast<Expr*>(expr2);
4221
4222 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4223
4224 // The conditional expression is required to be a constant expression.
4225 llvm::APSInt condEval(32);
4226 SourceLocation ExpLoc;
4227 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004228 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4229 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004230
4231 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4232 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4233 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004234 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4235 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004236}
4237
Steve Naroff52a81c02008-09-03 18:15:37 +00004238//===----------------------------------------------------------------------===//
4239// Clang Extensions.
4240//===----------------------------------------------------------------------===//
4241
4242/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004243void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004244 // Analyze block parameters.
4245 BlockSemaInfo *BSI = new BlockSemaInfo();
4246
4247 // Add BSI to CurBlock.
4248 BSI->PrevBlockInfo = CurBlock;
4249 CurBlock = BSI;
4250
4251 BSI->ReturnType = 0;
4252 BSI->TheScope = BlockScope;
4253
Steve Naroff52059382008-10-10 01:28:17 +00004254 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004255 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004256}
4257
Mike Stumpc1fddff2009-02-04 22:31:32 +00004258void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4259 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4260
4261 if (ParamInfo.getNumTypeObjects() == 0
4262 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4263 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4264
4265 // The type is entirely optional as well, if none, use DependentTy.
4266 if (T.isNull())
4267 T = Context.DependentTy;
4268
4269 // The parameter list is optional, if there was none, assume ().
4270 if (!T->isFunctionType())
4271 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4272
4273 CurBlock->hasPrototype = true;
4274 CurBlock->isVariadic = false;
4275 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4276 .getTypePtr();
4277
4278 if (!RetTy->isDependentType())
4279 CurBlock->ReturnType = RetTy;
4280 return;
4281 }
4282
Steve Naroff52a81c02008-09-03 18:15:37 +00004283 // Analyze arguments to block.
4284 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4285 "Not a function declarator!");
4286 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004287
Steve Naroff52059382008-10-10 01:28:17 +00004288 CurBlock->hasPrototype = FTI.hasPrototype;
4289 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004290
4291 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4292 // no arguments, not a function that takes a single void argument.
4293 if (FTI.hasPrototype &&
4294 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4295 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4296 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4297 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004298 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004299 } else if (FTI.hasPrototype) {
4300 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004301 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4302 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004303 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4304
4305 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4306 .getTypePtr();
4307
4308 if (!RetTy->isDependentType())
4309 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004310 }
Steve Naroff52059382008-10-10 01:28:17 +00004311 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4312
4313 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4314 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4315 // If this has an identifier, add it to the scope stack.
4316 if ((*AI)->getIdentifier())
4317 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004318}
4319
4320/// ActOnBlockError - If there is an error parsing a block, this callback
4321/// is invoked to pop the information about the block from the action impl.
4322void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4323 // Ensure that CurBlock is deleted.
4324 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4325
4326 // Pop off CurBlock, handle nested blocks.
4327 CurBlock = CurBlock->PrevBlockInfo;
4328
4329 // FIXME: Delete the ParmVarDecl objects as well???
4330
4331}
4332
4333/// ActOnBlockStmtExpr - This is called when the body of a block statement
4334/// literal was successfully completed. ^(int x){...}
4335Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4336 Scope *CurScope) {
4337 // Ensure that CurBlock is deleted.
4338 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4339 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4340
Steve Naroff52059382008-10-10 01:28:17 +00004341 PopDeclContext();
4342
Steve Naroff52a81c02008-09-03 18:15:37 +00004343 // Pop off CurBlock, handle nested blocks.
4344 CurBlock = CurBlock->PrevBlockInfo;
4345
4346 QualType RetTy = Context.VoidTy;
4347 if (BSI->ReturnType)
4348 RetTy = QualType(BSI->ReturnType, 0);
4349
4350 llvm::SmallVector<QualType, 8> ArgTypes;
4351 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4352 ArgTypes.push_back(BSI->Params[i]->getType());
4353
4354 QualType BlockTy;
4355 if (!BSI->hasPrototype)
4356 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4357 else
4358 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004359 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004360
4361 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004362
Steve Naroff95029d92008-10-08 18:44:00 +00004363 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004364 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004365}
4366
Nate Begemanbd881ef2008-01-30 20:50:20 +00004367/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004368/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004369/// The number of arguments has already been validated to match the number of
4370/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004371static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4372 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004373 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004374 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004375 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4376 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004377
4378 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004379 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004380 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004381 return true;
4382}
4383
4384Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4385 SourceLocation *CommaLocs,
4386 SourceLocation BuiltinLoc,
4387 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004388 // __builtin_overload requires at least 2 arguments
4389 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004390 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4391 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004392
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004393 // The first argument is required to be a constant expression. It tells us
4394 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004395 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004396 Expr *NParamsExpr = Args[0];
4397 llvm::APSInt constEval(32);
4398 SourceLocation ExpLoc;
4399 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004400 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4401 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004402
4403 // Verify that the number of parameters is > 0
4404 unsigned NumParams = constEval.getZExtValue();
4405 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004406 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4407 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004408 // Verify that we have at least 1 + NumParams arguments to the builtin.
4409 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004410 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4411 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004412
4413 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004414 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004415 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004416 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4417 // UsualUnaryConversions will convert the function DeclRefExpr into a
4418 // pointer to function.
4419 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004420 const FunctionTypeProto *FnType = 0;
4421 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4422 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004423
4424 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4425 // parameters, and the number of parameters must match the value passed to
4426 // the builtin.
4427 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004428 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4429 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004430
4431 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004432 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004433 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004434 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004435 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004436 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4437 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004438 // Remember our match, and continue processing the remaining arguments
4439 // to catch any errors.
Steve Naroff774e4152009-01-21 00:14:39 +00004440 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004441 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004442 BuiltinLoc, RParenLoc);
4443 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004444 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004445 // Return the newly created OverloadExpr node, if we succeded in matching
4446 // exactly one of the candidate functions.
4447 if (OE)
4448 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004449
4450 // If we didn't find a matching function Expr in the __builtin_overload list
4451 // the return an error.
4452 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004453 for (unsigned i = 0; i != NumParams; ++i) {
4454 if (i != 0) typeNames += ", ";
4455 typeNames += Args[i+1]->getType().getAsString();
4456 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004457
Chris Lattner77d52da2008-11-20 06:06:08 +00004458 return Diag(BuiltinLoc, diag::err_overload_no_match)
4459 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004460}
4461
Anders Carlsson36760332007-10-15 20:28:48 +00004462Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4463 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004464 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004465 Expr *E = static_cast<Expr*>(expr);
4466 QualType T = QualType::getFromOpaquePtr(type);
4467
4468 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004469
4470 // Get the va_list type
4471 QualType VaListType = Context.getBuiltinVaListType();
4472 // Deal with implicit array decay; for example, on x86-64,
4473 // va_list is an array, but it's supposed to decay to
4474 // a pointer for va_arg.
4475 if (VaListType->isArrayType())
4476 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004477 // Make sure the input expression also decays appropriately.
4478 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004479
4480 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004481 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004482 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004483 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004484
4485 // FIXME: Warn if a non-POD type is passed in.
4486
Steve Naroff774e4152009-01-21 00:14:39 +00004487 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004488}
4489
Douglas Gregorad4b3792008-11-29 04:51:27 +00004490Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4491 // The type of __null will be int or long, depending on the size of
4492 // pointers on the target.
4493 QualType Ty;
4494 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4495 Ty = Context.IntTy;
4496 else
4497 Ty = Context.LongTy;
4498
Steve Naroff774e4152009-01-21 00:14:39 +00004499 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004500}
4501
Chris Lattner005ed752008-01-04 18:04:52 +00004502bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4503 SourceLocation Loc,
4504 QualType DstType, QualType SrcType,
4505 Expr *SrcExpr, const char *Flavor) {
4506 // Decode the result (notice that AST's are still created for extensions).
4507 bool isInvalid = false;
4508 unsigned DiagKind;
4509 switch (ConvTy) {
4510 default: assert(0 && "Unknown conversion type");
4511 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004512 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004513 DiagKind = diag::ext_typecheck_convert_pointer_int;
4514 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004515 case IntToPointer:
4516 DiagKind = diag::ext_typecheck_convert_int_pointer;
4517 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004518 case IncompatiblePointer:
4519 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4520 break;
4521 case FunctionVoidPointer:
4522 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4523 break;
4524 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004525 // If the qualifiers lost were because we were applying the
4526 // (deprecated) C++ conversion from a string literal to a char*
4527 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4528 // Ideally, this check would be performed in
4529 // CheckPointerTypesForAssignment. However, that would require a
4530 // bit of refactoring (so that the second argument is an
4531 // expression, rather than a type), which should be done as part
4532 // of a larger effort to fix CheckPointerTypesForAssignment for
4533 // C++ semantics.
4534 if (getLangOptions().CPlusPlus &&
4535 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4536 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004537 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4538 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004539 case IntToBlockPointer:
4540 DiagKind = diag::err_int_to_block_pointer;
4541 break;
4542 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004543 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004544 break;
Steve Naroff19608432008-10-14 22:18:38 +00004545 case IncompatibleObjCQualifiedId:
4546 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4547 // it can give a more specific diagnostic.
4548 DiagKind = diag::warn_incompatible_qualified_id;
4549 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004550 case IncompatibleVectors:
4551 DiagKind = diag::warn_incompatible_vectors;
4552 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004553 case Incompatible:
4554 DiagKind = diag::err_typecheck_convert_incompatible;
4555 isInvalid = true;
4556 break;
4557 }
4558
Chris Lattner271d4c22008-11-24 05:29:24 +00004559 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4560 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004561 return isInvalid;
4562}
Anders Carlssond5201b92008-11-30 19:50:32 +00004563
4564bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4565{
4566 Expr::EvalResult EvalResult;
4567
4568 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4569 EvalResult.HasSideEffects) {
4570 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4571
4572 if (EvalResult.Diag) {
4573 // We only show the note if it's not the usual "invalid subexpression"
4574 // or if it's actually in a subexpression.
4575 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4576 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4577 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4578 }
4579
4580 return true;
4581 }
4582
4583 if (EvalResult.Diag) {
4584 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4585 E->getSourceRange();
4586
4587 // Print the reason it's not a constant.
4588 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4589 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4590 }
4591
4592 if (Result)
4593 *Result = EvalResult.Val.getInt();
4594 return false;
4595}