blob: ad4f297388ca799c1872cda3de1578a1bc2d627b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner2cb744b2009-02-15 22:43:40 +000029
30/// DiagnoseUseOfDeprecatedDeclImpl - If the specified decl is deprecated or
31// unavailable, emit the corresponding diagnostics.
32void Sema::DiagnoseUseOfDeprecatedDeclImpl(NamedDecl *D, SourceLocation Loc) {
33 // See if the decl is deprecated.
34 if (D->getAttr<DeprecatedAttr>()) {
Chris Lattnerfb1bb822009-02-16 19:35:30 +000035 // Implementing deprecated stuff requires referencing depreated stuff. Don't
36 // warn if we are implementing a deprecated construct.
37 bool isSilenced = false;
38
39 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
40 // If this reference happens *in* a deprecated function or method, don't
41 // warn.
42 isSilenced = ND->getAttr<DeprecatedAttr>();
43
44 // If this is an Objective-C method implementation, check to see if the
45 // method was deprecated on the declaration, not the definition.
46 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
47 // The semantic decl context of a ObjCMethodDecl is the
48 // ObjCImplementationDecl.
49 if (ObjCImplementationDecl *Impl
50 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
51
52 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
53 MD->isInstanceMethod());
54 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
55 }
56 }
57 }
58
59 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000060 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
61 }
62
63 // See if hte decl is unavailable.
64 if (D->getAttr<UnavailableAttr>())
65 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
66}
67
Chris Lattner299b8842008-07-25 21:10:04 +000068//===----------------------------------------------------------------------===//
69// Standard Promotions and Conversions
70//===----------------------------------------------------------------------===//
71
Chris Lattner299b8842008-07-25 21:10:04 +000072/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
73void Sema::DefaultFunctionArrayConversion(Expr *&E) {
74 QualType Ty = E->getType();
75 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
76
Chris Lattner299b8842008-07-25 21:10:04 +000077 if (Ty->isFunctionType())
78 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000079 else if (Ty->isArrayType()) {
80 // In C90 mode, arrays only promote to pointers if the array expression is
81 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
82 // type 'array of type' is converted to an expression that has type 'pointer
83 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
84 // that has type 'array of type' ...". The relevant change is "an lvalue"
85 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000086 //
87 // C++ 4.2p1:
88 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
89 // T" can be converted to an rvalue of type "pointer to T".
90 //
91 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
92 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000093 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
94 }
Chris Lattner299b8842008-07-25 21:10:04 +000095}
96
97/// UsualUnaryConversions - Performs various conversions that are common to most
98/// operators (C99 6.3). The conversions of array and function types are
99/// sometimes surpressed. For example, the array->pointer conversion doesn't
100/// apply if the array is an argument to the sizeof or address (&) operators.
101/// In these instances, this routine should *not* be called.
102Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
103 QualType Ty = Expr->getType();
104 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
105
Chris Lattner299b8842008-07-25 21:10:04 +0000106 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
107 ImpCastExprToType(Expr, Context.IntTy);
108 else
109 DefaultFunctionArrayConversion(Expr);
110
111 return Expr;
112}
113
Chris Lattner9305c3d2008-07-25 22:25:12 +0000114/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
115/// do not have a prototype. Arguments that have type float are promoted to
116/// double. All other argument types are converted by UsualUnaryConversions().
117void Sema::DefaultArgumentPromotion(Expr *&Expr) {
118 QualType Ty = Expr->getType();
119 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
120
121 // If this is a 'float' (CVR qualified or typedef) promote to double.
122 if (const BuiltinType *BT = Ty->getAsBuiltinType())
123 if (BT->getKind() == BuiltinType::Float)
124 return ImpCastExprToType(Expr, Context.DoubleTy);
125
126 UsualUnaryConversions(Expr);
127}
128
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000129// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
130// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000131void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000132 DefaultArgumentPromotion(Expr);
133
134 if (!Expr->getType()->isPODType()) {
135 Diag(Expr->getLocStart(),
136 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
137 Expr->getType() << CT;
138 }
139}
140
141
Chris Lattner299b8842008-07-25 21:10:04 +0000142/// UsualArithmeticConversions - Performs various conversions that are common to
143/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
144/// routine returns the first non-arithmetic type found. The client is
145/// responsible for emitting appropriate error diagnostics.
146/// FIXME: verify the conversion rules for "complex int" are consistent with
147/// GCC.
148QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
149 bool isCompAssign) {
150 if (!isCompAssign) {
151 UsualUnaryConversions(lhsExpr);
152 UsualUnaryConversions(rhsExpr);
153 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000154
Chris Lattner299b8842008-07-25 21:10:04 +0000155 // For conversion purposes, we ignore any qualifiers.
156 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000157 QualType lhs =
158 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
159 QualType rhs =
160 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000161
162 // If both types are identical, no conversion is needed.
163 if (lhs == rhs)
164 return lhs;
165
166 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
167 // The caller can deal with this (e.g. pointer + int).
168 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
169 return lhs;
170
171 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
172 if (!isCompAssign) {
173 ImpCastExprToType(lhsExpr, destType);
174 ImpCastExprToType(rhsExpr, destType);
175 }
176 return destType;
177}
178
179QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
180 // Perform the usual unary conversions. We do this early so that
181 // integral promotions to "int" can allow us to exit early, in the
182 // lhs == rhs check. Also, for conversion purposes, we ignore any
183 // qualifiers. For example, "const float" and "float" are
184 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000185 if (lhs->isPromotableIntegerType())
186 lhs = Context.IntTy;
187 else
188 lhs = lhs.getUnqualifiedType();
189 if (rhs->isPromotableIntegerType())
190 rhs = Context.IntTy;
191 else
192 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000193
Chris Lattner299b8842008-07-25 21:10:04 +0000194 // If both types are identical, no conversion is needed.
195 if (lhs == rhs)
196 return lhs;
197
198 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
199 // The caller can deal with this (e.g. pointer + int).
200 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
201 return lhs;
202
203 // At this point, we have two different arithmetic types.
204
205 // Handle complex types first (C99 6.3.1.8p1).
206 if (lhs->isComplexType() || rhs->isComplexType()) {
207 // if we have an integer operand, the result is the complex type.
208 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
209 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000210 return lhs;
211 }
212 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
213 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000214 return rhs;
215 }
216 // This handles complex/complex, complex/float, or float/complex.
217 // When both operands are complex, the shorter operand is converted to the
218 // type of the longer, and that is the type of the result. This corresponds
219 // to what is done when combining two real floating-point operands.
220 // The fun begins when size promotion occur across type domains.
221 // From H&S 6.3.4: When one operand is complex and the other is a real
222 // floating-point type, the less precise type is converted, within it's
223 // real or complex domain, to the precision of the other type. For example,
224 // when combining a "long double" with a "double _Complex", the
225 // "double _Complex" is promoted to "long double _Complex".
226 int result = Context.getFloatingTypeOrder(lhs, rhs);
227
228 if (result > 0) { // The left side is bigger, convert rhs.
229 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000230 } else if (result < 0) { // The right side is bigger, convert lhs.
231 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000232 }
233 // At this point, lhs and rhs have the same rank/size. Now, make sure the
234 // domains match. This is a requirement for our implementation, C99
235 // does not require this promotion.
236 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
237 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000238 return rhs;
239 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000240 return lhs;
241 }
242 }
243 return lhs; // The domain/size match exactly.
244 }
245 // Now handle "real" floating types (i.e. float, double, long double).
246 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
247 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000248 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000249 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000250 return lhs;
251 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000252 if (rhs->isComplexIntegerType()) {
253 // convert rhs to the complex floating point type.
254 return Context.getComplexType(lhs);
255 }
256 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000257 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000258 return rhs;
259 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000260 if (lhs->isComplexIntegerType()) {
261 // convert lhs to the complex floating point type.
262 return Context.getComplexType(rhs);
263 }
Chris Lattner299b8842008-07-25 21:10:04 +0000264 // We have two real floating types, float/complex combos were handled above.
265 // Convert the smaller operand to the bigger result.
266 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000267 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000268 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000269 assert(result < 0 && "illegal float comparison");
270 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000271 }
272 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
273 // Handle GCC complex int extension.
274 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
275 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
276
277 if (lhsComplexInt && rhsComplexInt) {
278 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000279 rhsComplexInt->getElementType()) >= 0)
280 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000281 return rhs;
282 } else if (lhsComplexInt && rhs->isIntegerType()) {
283 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000284 return lhs;
285 } else if (rhsComplexInt && lhs->isIntegerType()) {
286 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000287 return rhs;
288 }
289 }
290 // Finally, we have two differing integer types.
291 // The rules for this case are in C99 6.3.1.8
292 int compare = Context.getIntegerTypeOrder(lhs, rhs);
293 bool lhsSigned = lhs->isSignedIntegerType(),
294 rhsSigned = rhs->isSignedIntegerType();
295 QualType destType;
296 if (lhsSigned == rhsSigned) {
297 // Same signedness; use the higher-ranked type
298 destType = compare >= 0 ? lhs : rhs;
299 } else if (compare != (lhsSigned ? 1 : -1)) {
300 // The unsigned type has greater than or equal rank to the
301 // signed type, so use the unsigned type
302 destType = lhsSigned ? rhs : lhs;
303 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
304 // The two types are different widths; if we are here, that
305 // means the signed type is larger than the unsigned type, so
306 // use the signed type.
307 destType = lhsSigned ? lhs : rhs;
308 } else {
309 // The signed type is higher-ranked than the unsigned type,
310 // but isn't actually any bigger (like unsigned int and long
311 // on most 32-bit systems). Use the unsigned type corresponding
312 // to the signed type.
313 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
314 }
Chris Lattner299b8842008-07-25 21:10:04 +0000315 return destType;
316}
317
318//===----------------------------------------------------------------------===//
319// Semantic Analysis for various Expression Types
320//===----------------------------------------------------------------------===//
321
322
Steve Naroff87d58b42007-09-16 03:34:24 +0000323/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000324/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
325/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
326/// multiple tokens. However, the common case is that StringToks points to one
327/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000328///
329Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000330Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000331 assert(NumStringToks && "Must have at least one string!");
332
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000333 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000334 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000335 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000336
337 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
338 for (unsigned i = 0; i != NumStringToks; ++i)
339 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000340
Chris Lattnera6dcce32008-02-11 00:02:17 +0000341 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000342 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000343 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000344
345 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
346 if (getLangOptions().CPlusPlus)
347 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000348
Chris Lattnera6dcce32008-02-11 00:02:17 +0000349 // Get an array type for the string, according to C99 6.4.5. This includes
350 // the nul terminator character as well as the string length for pascal
351 // strings.
352 StrTy = Context.getConstantArrayType(StrTy,
353 llvm::APInt(32, Literal.GetStringLength()+1),
354 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355
Chris Lattner4b009652007-07-25 00:24:17 +0000356 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000357 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000358 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000359 Literal.AnyWide, StrTy,
360 StringToks[0].getLocation(),
361 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000362}
363
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000364/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
365/// CurBlock to VD should cause it to be snapshotted (as we do for auto
366/// variables defined outside the block) or false if this is not needed (e.g.
367/// for values inside the block or for globals).
368///
369/// FIXME: This will create BlockDeclRefExprs for global variables,
370/// function references, etc which is suboptimal :) and breaks
371/// things like "integer constant expression" tests.
372static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
373 ValueDecl *VD) {
374 // If the value is defined inside the block, we couldn't snapshot it even if
375 // we wanted to.
376 if (CurBlock->TheDecl == VD->getDeclContext())
377 return false;
378
379 // If this is an enum constant or function, it is constant, don't snapshot.
380 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
381 return false;
382
383 // If this is a reference to an extern, static, or global variable, no need to
384 // snapshot it.
385 // FIXME: What about 'const' variables in C++?
386 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
387 return Var->hasLocalStorage();
388
389 return true;
390}
391
392
393
Steve Naroff0acc9c92007-09-15 18:49:24 +0000394/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000395/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000396/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000397/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000398/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000399Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
400 IdentifierInfo &II,
401 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000402 const CXXScopeSpec *SS,
403 bool isAddressOfOperand) {
404 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000405 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000406}
407
Douglas Gregor566782a2009-01-06 05:10:23 +0000408/// BuildDeclRefExpr - Build either a DeclRefExpr or a
409/// QualifiedDeclRefExpr based on whether or not SS is a
410/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000411DeclRefExpr *
412Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
413 bool TypeDependent, bool ValueDependent,
414 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000415 if (SS && !SS->isEmpty())
416 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000417 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000418 else
419 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000420}
421
Douglas Gregor723d3332009-01-07 00:43:41 +0000422/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
423/// variable corresponding to the anonymous union or struct whose type
424/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000425static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000426 assert(Record->isAnonymousStructOrUnion() &&
427 "Record must be an anonymous struct or union!");
428
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000429 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000430 // be an O(1) operation rather than a slow walk through DeclContext's
431 // vector (which itself will be eliminated). DeclGroups might make
432 // this even better.
433 DeclContext *Ctx = Record->getDeclContext();
434 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
435 DEnd = Ctx->decls_end();
436 D != DEnd; ++D) {
437 if (*D == Record) {
438 // The object for the anonymous struct/union directly
439 // follows its type in the list of declarations.
440 ++D;
441 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000442 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000443 return *D;
444 }
445 }
446
447 assert(false && "Missing object for anonymous record");
448 return 0;
449}
450
Sebastian Redlcd883f72009-01-18 18:53:16 +0000451Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000452Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
453 FieldDecl *Field,
454 Expr *BaseObjectExpr,
455 SourceLocation OpLoc) {
456 assert(Field->getDeclContext()->isRecord() &&
457 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
458 && "Field must be stored inside an anonymous struct or union");
459
460 // Construct the sequence of field member references
461 // we'll have to perform to get to the field in the anonymous
462 // union/struct. The list of members is built from the field
463 // outward, so traverse it backwards to go from an object in
464 // the current context to the field we found.
465 llvm::SmallVector<FieldDecl *, 4> AnonFields;
466 AnonFields.push_back(Field);
467 VarDecl *BaseObject = 0;
468 DeclContext *Ctx = Field->getDeclContext();
469 do {
470 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000471 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000472 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
473 AnonFields.push_back(AnonField);
474 else {
475 BaseObject = cast<VarDecl>(AnonObject);
476 break;
477 }
478 Ctx = Ctx->getParent();
479 } while (Ctx->isRecord() &&
480 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
481
482 // Build the expression that refers to the base object, from
483 // which we will build a sequence of member references to each
484 // of the anonymous union objects and, eventually, the field we
485 // found via name lookup.
486 bool BaseObjectIsPointer = false;
487 unsigned ExtraQuals = 0;
488 if (BaseObject) {
489 // BaseObject is an anonymous struct/union variable (and is,
490 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000491 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000492 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000493 SourceLocation());
494 ExtraQuals
495 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
496 } else if (BaseObjectExpr) {
497 // The caller provided the base object expression. Determine
498 // whether its a pointer and whether it adds any qualifiers to the
499 // anonymous struct/union fields we're looking into.
500 QualType ObjectType = BaseObjectExpr->getType();
501 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
502 BaseObjectIsPointer = true;
503 ObjectType = ObjectPtr->getPointeeType();
504 }
505 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
506 } else {
507 // We've found a member of an anonymous struct/union that is
508 // inside a non-anonymous struct/union, so in a well-formed
509 // program our base object expression is "this".
510 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
511 if (!MD->isStatic()) {
512 QualType AnonFieldType
513 = Context.getTagDeclType(
514 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
515 QualType ThisType = Context.getTagDeclType(MD->getParent());
516 if ((Context.getCanonicalType(AnonFieldType)
517 == Context.getCanonicalType(ThisType)) ||
518 IsDerivedFrom(ThisType, AnonFieldType)) {
519 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000520 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000521 MD->getThisType(Context));
522 BaseObjectIsPointer = true;
523 }
524 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000525 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
526 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000527 }
528 ExtraQuals = MD->getTypeQualifiers();
529 }
530
531 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000532 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
533 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000534 }
535
536 // Build the implicit member references to the field of the
537 // anonymous struct/union.
538 Expr *Result = BaseObjectExpr;
539 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
540 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
541 FI != FIEnd; ++FI) {
542 QualType MemberType = (*FI)->getType();
543 if (!(*FI)->isMutable()) {
544 unsigned combinedQualifiers
545 = MemberType.getCVRQualifiers() | ExtraQuals;
546 MemberType = MemberType.getQualifiedType(combinedQualifiers);
547 }
Steve Naroff774e4152009-01-21 00:14:39 +0000548 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
549 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000550 BaseObjectIsPointer = false;
551 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
552 OpLoc = SourceLocation();
553 }
554
Sebastian Redlcd883f72009-01-18 18:53:16 +0000555 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000556}
557
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000558/// ActOnDeclarationNameExpr - The parser has read some kind of name
559/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
560/// performs lookup on that name and returns an expression that refers
561/// to that name. This routine isn't directly called from the parser,
562/// because the parser doesn't know about DeclarationName. Rather,
563/// this routine is called by ActOnIdentifierExpr,
564/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
565/// which form the DeclarationName from the corresponding syntactic
566/// forms.
567///
568/// HasTrailingLParen indicates whether this identifier is used in a
569/// function call context. LookupCtx is only used for a C++
570/// qualified-id (foo::bar) to indicate the class or namespace that
571/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000572///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000573/// isAddressOfOperand means that this expression is the direct operand
574/// of an address-of operator. This matters because this is the only
575/// situation where a qualified name referencing a non-static member may
576/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000577Sema::OwningExprResult
578Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
579 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000580 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000581 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000582 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000583 if (SS && SS->isInvalid())
584 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000585 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
586 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000587
Douglas Gregor09be81b2009-02-04 17:27:36 +0000588 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000589 if (Lookup.isAmbiguous()) {
590 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
591 SS && SS->isSet() ? SS->getRange()
592 : SourceRange());
593 return ExprError();
594 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000595 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000596
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000597 // If this reference is in an Objective-C method, then ivar lookup happens as
598 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000599 IdentifierInfo *II = Name.getAsIdentifierInfo();
600 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000601 // There are two cases to handle here. 1) scoped lookup could have failed,
602 // in which case we should look for an ivar. 2) scoped lookup could have
603 // found a decl, but that decl is outside the current method (i.e. a global
604 // variable). In these two cases, we do a lookup for an ivar with this
605 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000606 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000607 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000608 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000609 // Check if referencing a field with __attribute__((deprecated)).
610 DiagnoseUseOfDeprecatedDecl(IV, Loc);
611
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000612 // FIXME: This should use a new expr for a direct reference, don't turn
613 // this into Self->ivar, just return a BareIVarExpr or something.
614 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000615 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000616 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
617 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000618 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000619 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000621 }
622 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000623 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000624 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000625 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000626 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000627 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000628 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000629 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000630
631 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
632 HasTrailingLParen && D == 0) {
633 // We've seen something of the form
634 //
635 // identifier(
636 //
637 // and we did not find any entity by the name
638 // "identifier". However, this identifier is still subject to
639 // argument-dependent lookup, so keep track of the name.
640 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
641 Context.OverloadTy,
642 Loc));
643 }
644
Chris Lattner4b009652007-07-25 00:24:17 +0000645 if (D == 0) {
646 // Otherwise, this could be an implicitly declared function reference (legal
647 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000648 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000649 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000650 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000651 else {
652 // If this name wasn't predeclared and if this is not a function call,
653 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000654 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000655 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
656 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000657 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
658 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000659 return ExprError(Diag(Loc, diag::err_undeclared_use)
660 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000661 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000662 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000663 }
664 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000665
Sebastian Redl0c9da212009-02-03 20:19:35 +0000666 // If this is an expression of the form &Class::member, don't build an
667 // implicit member ref, because we want a pointer to the member in general,
668 // not any specific instance's member.
669 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000670 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000671 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000672 QualType DType;
673 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
674 DType = FD->getType().getNonReferenceType();
675 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
676 DType = Method->getType();
677 } else if (isa<OverloadedFunctionDecl>(D)) {
678 DType = Context.OverloadTy;
679 }
680 // Could be an inner type. That's diagnosed below, so ignore it here.
681 if (!DType.isNull()) {
682 // The pointer is type- and value-dependent if it points into something
683 // dependent.
684 bool Dependent = false;
685 for (; DC; DC = DC->getParent()) {
686 // FIXME: could stop early at namespace scope.
687 if (DC->isRecord()) {
688 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
689 if (Context.getTypeDeclType(Record)->isDependentType()) {
690 Dependent = true;
691 break;
692 }
693 }
694 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000695 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000696 }
697 }
698 }
699
Douglas Gregor723d3332009-01-07 00:43:41 +0000700 // We may have found a field within an anonymous union or struct
701 // (C++ [class.union]).
702 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
703 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
704 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000705
Douglas Gregor3257fb52008-12-22 05:46:06 +0000706 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
707 if (!MD->isStatic()) {
708 // C++ [class.mfct.nonstatic]p2:
709 // [...] if name lookup (3.4.1) resolves the name in the
710 // id-expression to a nonstatic nontype member of class X or of
711 // a base class of X, the id-expression is transformed into a
712 // class member access expression (5.2.5) using (*this) (9.3.2)
713 // as the postfix-expression to the left of the '.' operator.
714 DeclContext *Ctx = 0;
715 QualType MemberType;
716 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
717 Ctx = FD->getDeclContext();
718 MemberType = FD->getType();
719
720 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
721 MemberType = RefType->getPointeeType();
722 else if (!FD->isMutable()) {
723 unsigned combinedQualifiers
724 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
725 MemberType = MemberType.getQualifiedType(combinedQualifiers);
726 }
727 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
728 if (!Method->isStatic()) {
729 Ctx = Method->getParent();
730 MemberType = Method->getType();
731 }
732 } else if (OverloadedFunctionDecl *Ovl
733 = dyn_cast<OverloadedFunctionDecl>(D)) {
734 for (OverloadedFunctionDecl::function_iterator
735 Func = Ovl->function_begin(),
736 FuncEnd = Ovl->function_end();
737 Func != FuncEnd; ++Func) {
738 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
739 if (!DMethod->isStatic()) {
740 Ctx = Ovl->getDeclContext();
741 MemberType = Context.OverloadTy;
742 break;
743 }
744 }
745 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000746
747 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000748 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
749 QualType ThisType = Context.getTagDeclType(MD->getParent());
750 if ((Context.getCanonicalType(CtxType)
751 == Context.getCanonicalType(ThisType)) ||
752 IsDerivedFrom(ThisType, CtxType)) {
753 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000754 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000755 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000756 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000757 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000758 }
759 }
760 }
761 }
762
Douglas Gregor8acb7272008-12-11 16:49:14 +0000763 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000764 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
765 if (MD->isStatic())
766 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000767 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
768 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000769 }
770
Douglas Gregor3257fb52008-12-22 05:46:06 +0000771 // Any other ways we could have found the field in a well-formed
772 // program would have been turned into implicit member expressions
773 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000774 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
775 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000776 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000777
Chris Lattner4b009652007-07-25 00:24:17 +0000778 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000779 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000780 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000781 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000782 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000783 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000784
Steve Naroffd6163f32008-09-05 22:11:13 +0000785 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000786 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000787 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
788 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000789 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
790 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
791 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000792 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000793
Chris Lattnerd9037472009-02-15 01:38:09 +0000794 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner2cb744b2009-02-15 22:43:40 +0000795 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattnerd9037472009-02-15 01:38:09 +0000796
Douglas Gregor48840c72008-12-10 23:01:14 +0000797 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000798 // Warn about constructs like:
799 // if (void *X = foo()) { ... } else { X }.
800 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000801 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
802 Scope *CheckS = S;
803 while (CheckS) {
804 if (CheckS->isWithinElse() &&
805 CheckS->getControlParent()->isDeclScope(Var)) {
806 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000807 ExprError(Diag(Loc, diag::warn_value_always_false)
808 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000809 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000810 ExprError(Diag(Loc, diag::warn_value_always_zero)
811 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000812 break;
813 }
814
815 // Move up one more control parent to check again.
816 CheckS = CheckS->getControlParent();
817 if (CheckS)
818 CheckS = CheckS->getParent();
819 }
820 }
821 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000822
823 // Only create DeclRefExpr's for valid Decl's.
824 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000825 return ExprError();
826
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000827 // If the identifier reference is inside a block, and it refers to a value
828 // that is outside the block, create a BlockDeclRefExpr instead of a
829 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
830 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000831 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000832 // We do not do this for things like enum constants, global variables, etc,
833 // as they do not get snapshotted.
834 //
835 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000836 // The BlocksAttr indicates the variable is bound by-reference.
837 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000838 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000839 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000840
Steve Naroff52059382008-10-10 01:28:17 +0000841 // Variable will be bound by-copy, make it const within the closure.
842 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000843 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000844 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000845 }
846 // If this reference is not in a block or if the referenced variable is
847 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000848
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000849 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000850 bool ValueDependent = false;
851 if (getLangOptions().CPlusPlus) {
852 // C++ [temp.dep.expr]p3:
853 // An id-expression is type-dependent if it contains:
854 // - an identifier that was declared with a dependent type,
855 if (VD->getType()->isDependentType())
856 TypeDependent = true;
857 // - FIXME: a template-id that is dependent,
858 // - a conversion-function-id that specifies a dependent type,
859 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
860 Name.getCXXNameType()->isDependentType())
861 TypeDependent = true;
862 // - a nested-name-specifier that contains a class-name that
863 // names a dependent type.
864 else if (SS && !SS->isEmpty()) {
865 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
866 DC; DC = DC->getParent()) {
867 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000868 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000869 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
870 if (Context.getTypeDeclType(Record)->isDependentType()) {
871 TypeDependent = true;
872 break;
873 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000874 }
875 }
876 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000877
Douglas Gregora5d84612008-12-10 20:57:37 +0000878 // C++ [temp.dep.constexpr]p2:
879 //
880 // An identifier is value-dependent if it is:
881 // - a name declared with a dependent type,
882 if (TypeDependent)
883 ValueDependent = true;
884 // - the name of a non-type template parameter,
885 else if (isa<NonTypeTemplateParmDecl>(VD))
886 ValueDependent = true;
887 // - a constant with integral or enumeration type and is
888 // initialized with an expression that is value-dependent
889 // (FIXME!).
890 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000891
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
893 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000894}
895
Sebastian Redlcd883f72009-01-18 18:53:16 +0000896Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
897 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000898 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000899
Chris Lattner4b009652007-07-25 00:24:17 +0000900 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000901 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000902 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
903 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
904 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000905 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000906
Chris Lattner7e637512008-01-12 08:14:25 +0000907 // Pre-defined identifiers are of type char[x], where x is the length of the
908 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000909 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000910 if (FunctionDecl *FD = getCurFunctionDecl())
911 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000912 else if (ObjCMethodDecl *MD = getCurMethodDecl())
913 Length = MD->getSynthesizedMethodSize();
914 else {
915 Diag(Loc, diag::ext_predef_outside_function);
916 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
917 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
918 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000919
920
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000921 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000922 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000923 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000924 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000925}
926
Sebastian Redlcd883f72009-01-18 18:53:16 +0000927Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000928 llvm::SmallString<16> CharBuffer;
929 CharBuffer.resize(Tok.getLength());
930 const char *ThisTokBegin = &CharBuffer[0];
931 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000932
Chris Lattner4b009652007-07-25 00:24:17 +0000933 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
934 Tok.getLocation(), PP);
935 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000936 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000937
938 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
939
Sebastian Redl75324932009-01-20 22:23:13 +0000940 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
941 Literal.isWide(),
942 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000943}
944
Sebastian Redlcd883f72009-01-18 18:53:16 +0000945Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
946 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000947 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
948 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000949 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000950 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000951 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000952 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000953 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000954
Chris Lattner4b009652007-07-25 00:24:17 +0000955 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000956 // Add padding so that NumericLiteralParser can overread by one character.
957 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000958 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000959
Chris Lattner4b009652007-07-25 00:24:17 +0000960 // Get the spelling of the token, which eliminates trigraphs, etc.
961 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000962
Chris Lattner4b009652007-07-25 00:24:17 +0000963 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
964 Tok.getLocation(), PP);
965 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966 return ExprError();
967
Chris Lattner1de66eb2007-08-26 03:42:43 +0000968 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969
Chris Lattner1de66eb2007-08-26 03:42:43 +0000970 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000971 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000972 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000973 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000974 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000975 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000976 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000977 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000978
979 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
980
Ted Kremenekddedbe22007-11-29 00:56:49 +0000981 // isExact will be set by GetFloatValue().
982 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000983 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
984 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000985
Chris Lattner1de66eb2007-08-26 03:42:43 +0000986 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000987 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000988 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000989 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000990
Neil Booth7421e9c2007-08-29 22:00:19 +0000991 // long long is a C99 feature.
992 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000993 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000994 Diag(Tok.getLocation(), diag::ext_longlong);
995
Chris Lattner4b009652007-07-25 00:24:17 +0000996 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000997 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000998
Chris Lattner4b009652007-07-25 00:24:17 +0000999 if (Literal.GetIntegerValue(ResultVal)) {
1000 // If this value didn't fit into uintmax_t, warn and force to ull.
1001 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001002 Ty = Context.UnsignedLongLongTy;
1003 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001004 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001005 } else {
1006 // If this value fits into a ULL, try to figure out what else it fits into
1007 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001008
Chris Lattner4b009652007-07-25 00:24:17 +00001009 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1010 // be an unsigned int.
1011 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1012
1013 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001014 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001015 if (!Literal.isLong && !Literal.isLongLong) {
1016 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001017 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001018
Chris Lattner4b009652007-07-25 00:24:17 +00001019 // Does it fit in a unsigned int?
1020 if (ResultVal.isIntN(IntSize)) {
1021 // Does it fit in a signed int?
1022 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001023 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001024 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001025 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001026 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001027 }
Chris Lattner4b009652007-07-25 00:24:17 +00001028 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001031 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001032 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033
Chris Lattner4b009652007-07-25 00:24:17 +00001034 // Does it fit in a unsigned long?
1035 if (ResultVal.isIntN(LongSize)) {
1036 // Does it fit in a signed long?
1037 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001038 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001039 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001040 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001041 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001042 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043 }
1044
Chris Lattner4b009652007-07-25 00:24:17 +00001045 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001046 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001047 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001048
Chris Lattner4b009652007-07-25 00:24:17 +00001049 // Does it fit in a unsigned long long?
1050 if (ResultVal.isIntN(LongLongSize)) {
1051 // Does it fit in a signed long long?
1052 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001053 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001054 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001055 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001056 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001057 }
1058 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001059
Chris Lattner4b009652007-07-25 00:24:17 +00001060 // If we still couldn't decide a type, we probably have something that
1061 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001062 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001063 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001064 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001065 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001066 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001067
Chris Lattnere4068872008-05-09 05:59:00 +00001068 if (ResultVal.getBitWidth() != Width)
1069 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001070 }
Sebastian Redl75324932009-01-20 22:23:13 +00001071 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001072 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001073
Chris Lattner1de66eb2007-08-26 03:42:43 +00001074 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1075 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001076 Res = new (Context) ImaginaryLiteral(Res,
1077 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001078
1079 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001080}
1081
Sebastian Redlcd883f72009-01-18 18:53:16 +00001082Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1083 SourceLocation R, ExprArg Val) {
1084 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001085 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001086 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001087}
1088
1089/// The UsualUnaryConversions() function is *not* called by this routine.
1090/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001091bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1092 SourceLocation OpLoc,
1093 const SourceRange &ExprRange,
1094 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001095 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001096 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001097 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001098 if (isSizeof)
1099 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1100 return false;
1101 }
1102
1103 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001104 Diag(OpLoc, diag::ext_sizeof_void_type)
1105 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001106 return false;
1107 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001108
Chris Lattner159fe082009-01-24 19:46:37 +00001109 return DiagnoseIncompleteType(OpLoc, exprType,
1110 isSizeof ? diag::err_sizeof_incomplete_type :
1111 diag::err_alignof_incomplete_type,
1112 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001113}
1114
Chris Lattner8d9f7962009-01-24 20:17:12 +00001115bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1116 const SourceRange &ExprRange) {
1117 E = E->IgnoreParens();
1118
1119 // alignof decl is always ok.
1120 if (isa<DeclRefExpr>(E))
1121 return false;
1122
1123 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1124 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1125 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001126 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001127 return true;
1128 }
1129 // Other fields are ok.
1130 return false;
1131 }
1132 }
1133 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1134}
1135
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001136/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1137/// the same for @c alignof and @c __alignof
1138/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001139Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001140Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1141 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001142 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001143 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001144
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001145 QualType ArgTy;
1146 SourceRange Range;
1147 if (isType) {
1148 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1149 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001150
1151 // Verify that the operand is valid.
1152 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1153 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001154 } else {
1155 // Get the end location.
1156 Expr *ArgEx = (Expr *)TyOrEx;
1157 Range = ArgEx->getSourceRange();
1158 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001159
1160 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001161 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001162 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001163 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001164 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1165 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1166 isInvalid = true;
1167 } else {
1168 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1169 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001170
1171 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001172 DeleteExpr(ArgEx);
1173 return ExprError();
1174 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001175 }
1176
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001177 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001178 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001179 Context.getSizeType(), OpLoc,
1180 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001181}
1182
Chris Lattner5110ad52007-08-24 21:41:10 +00001183QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001184 DefaultFunctionArrayConversion(V);
1185
Chris Lattnera16e42d2007-08-26 05:39:26 +00001186 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001187 if (const ComplexType *CT = V->getType()->getAsComplexType())
1188 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001189
1190 // Otherwise they pass through real integer and floating point types here.
1191 if (V->getType()->isArithmeticType())
1192 return V->getType();
1193
1194 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001195 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001196 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001197}
1198
1199
Chris Lattner4b009652007-07-25 00:24:17 +00001200
Sebastian Redl8b769972009-01-19 00:08:26 +00001201Action::OwningExprResult
1202Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1203 tok::TokenKind Kind, ExprArg Input) {
1204 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001205
Chris Lattner4b009652007-07-25 00:24:17 +00001206 UnaryOperator::Opcode Opc;
1207 switch (Kind) {
1208 default: assert(0 && "Unknown unary op!");
1209 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1210 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1211 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001212
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001213 if (getLangOptions().CPlusPlus &&
1214 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1215 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001216 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001217 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1218
1219 // C++ [over.inc]p1:
1220 //
1221 // [...] If the function is a member function with one
1222 // parameter (which shall be of type int) or a non-member
1223 // function with two parameters (the second of which shall be
1224 // of type int), it defines the postfix increment operator ++
1225 // for objects of that type. When the postfix increment is
1226 // called as a result of using the ++ operator, the int
1227 // argument will have value zero.
1228 Expr *Args[2] = {
1229 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001230 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1231 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001232 };
1233
1234 // Build the candidate set for overloading
1235 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001236 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1237 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001238
1239 // Perform overload resolution.
1240 OverloadCandidateSet::iterator Best;
1241 switch (BestViableFunction(CandidateSet, Best)) {
1242 case OR_Success: {
1243 // We found a built-in operator or an overloaded operator.
1244 FunctionDecl *FnDecl = Best->Function;
1245
1246 if (FnDecl) {
1247 // We matched an overloaded operator. Build a call to that
1248 // operator.
1249
1250 // Convert the arguments.
1251 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1252 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001253 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001254 } else {
1255 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001256 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001257 FnDecl->getParamDecl(0)->getType(),
1258 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001259 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001260 }
1261
1262 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001263 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001264 = FnDecl->getType()->getAsFunctionType()->getResultType();
1265 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001266
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001267 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001268 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001269 SourceLocation());
1270 UsualUnaryConversions(FnExpr);
1271
Sebastian Redl8b769972009-01-19 00:08:26 +00001272 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001273 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1274 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001275 } else {
1276 // We matched a built-in operator. Convert the arguments, then
1277 // break out so that we will build the appropriate built-in
1278 // operator node.
1279 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1280 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001281 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001282
1283 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001284 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001285 }
1286
1287 case OR_No_Viable_Function:
1288 // No viable function; fall through to handling this as a
1289 // built-in operator, which will produce an error message for us.
1290 break;
1291
1292 case OR_Ambiguous:
1293 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1294 << UnaryOperator::getOpcodeStr(Opc)
1295 << Arg->getSourceRange();
1296 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001297 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001298 }
1299
1300 // Either we found no viable overloaded operator or we matched a
1301 // built-in operator. In either case, fall through to trying to
1302 // build a built-in operation.
1303 }
1304
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001305 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1306 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001307 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001308 return ExprError();
1309 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001310 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001311}
1312
Sebastian Redl8b769972009-01-19 00:08:26 +00001313Action::OwningExprResult
1314Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1315 ExprArg Idx, SourceLocation RLoc) {
1316 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1317 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001318
Douglas Gregor80723c52008-11-19 17:17:41 +00001319 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001320 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001321 LHSExp->getType()->isEnumeralType() ||
1322 RHSExp->getType()->isRecordType() ||
1323 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001324 // Add the appropriate overloaded operators (C++ [over.match.oper])
1325 // to the candidate set.
1326 OverloadCandidateSet CandidateSet;
1327 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001328 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1329 SourceRange(LLoc, RLoc)))
1330 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001331
Douglas Gregor80723c52008-11-19 17:17:41 +00001332 // Perform overload resolution.
1333 OverloadCandidateSet::iterator Best;
1334 switch (BestViableFunction(CandidateSet, Best)) {
1335 case OR_Success: {
1336 // We found a built-in operator or an overloaded operator.
1337 FunctionDecl *FnDecl = Best->Function;
1338
1339 if (FnDecl) {
1340 // We matched an overloaded operator. Build a call to that
1341 // operator.
1342
1343 // Convert the arguments.
1344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1345 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1346 PerformCopyInitialization(RHSExp,
1347 FnDecl->getParamDecl(0)->getType(),
1348 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001349 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001350 } else {
1351 // Convert the arguments.
1352 if (PerformCopyInitialization(LHSExp,
1353 FnDecl->getParamDecl(0)->getType(),
1354 "passing") ||
1355 PerformCopyInitialization(RHSExp,
1356 FnDecl->getParamDecl(1)->getType(),
1357 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001358 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001359 }
1360
1361 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001362 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001363 = FnDecl->getType()->getAsFunctionType()->getResultType();
1364 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001365
Douglas Gregor80723c52008-11-19 17:17:41 +00001366 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001367 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001368 SourceLocation());
1369 UsualUnaryConversions(FnExpr);
1370
Sebastian Redl8b769972009-01-19 00:08:26 +00001371 Base.release();
1372 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001373 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001374 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001375 } else {
1376 // We matched a built-in operator. Convert the arguments, then
1377 // break out so that we will build the appropriate built-in
1378 // operator node.
1379 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1380 "passing") ||
1381 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1382 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001383 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001384
1385 break;
1386 }
1387 }
1388
1389 case OR_No_Viable_Function:
1390 // No viable function; fall through to handling this as a
1391 // built-in operator, which will produce an error message for us.
1392 break;
1393
1394 case OR_Ambiguous:
1395 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1396 << "[]"
1397 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1398 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001399 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001400 }
1401
1402 // Either we found no viable overloaded operator or we matched a
1403 // built-in operator. In either case, fall through to trying to
1404 // build a built-in operation.
1405 }
1406
Chris Lattner4b009652007-07-25 00:24:17 +00001407 // Perform default conversions.
1408 DefaultFunctionArrayConversion(LHSExp);
1409 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001410
Chris Lattner4b009652007-07-25 00:24:17 +00001411 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1412
1413 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001414 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001415 // in the subscript position. As a result, we need to derive the array base
1416 // and index from the expression types.
1417 Expr *BaseExpr, *IndexExpr;
1418 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001419 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001420 BaseExpr = LHSExp;
1421 IndexExpr = RHSExp;
1422 // FIXME: need to deal with const...
1423 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001424 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001425 // Handle the uncommon case of "123[Ptr]".
1426 BaseExpr = RHSExp;
1427 IndexExpr = LHSExp;
1428 // FIXME: need to deal with const...
1429 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001430 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1431 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001432 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001433
Chris Lattner4b009652007-07-25 00:24:17 +00001434 // FIXME: need to deal with const...
1435 ResultType = VTy->getElementType();
1436 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001437 return ExprError(Diag(LHSExp->getLocStart(),
1438 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1439 }
Chris Lattner4b009652007-07-25 00:24:17 +00001440 // C99 6.5.2.1p1
1441 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001442 return ExprError(Diag(IndexExpr->getLocStart(),
1443 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001444
1445 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1446 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001447 // void (*)(int)) and pointers to incomplete types. Functions are not
1448 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001449 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001450 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001451 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001452 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001453
Sebastian Redl8b769972009-01-19 00:08:26 +00001454 Base.release();
1455 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001456 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1457 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001458}
1459
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001460QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001461CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001462 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001463 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001464
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001465 // The vector accessor can't exceed the number of elements.
1466 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001467
1468 // This flag determines whether or not the component is one of the four
1469 // special names that indicate a subset of exactly half the elements are
1470 // to be selected.
1471 bool HalvingSwizzle = false;
1472
1473 // This flag determines whether or not CompName has an 's' char prefix,
1474 // indicating that it is a string of hex values to be used as vector indices.
1475 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001476
1477 // Check that we've found one of the special components, or that the component
1478 // names must come from the same set.
1479 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001480 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1481 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001482 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001483 do
1484 compStr++;
1485 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001486 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001487 do
1488 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001489 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001490 }
Nate Begeman1486b502009-01-18 01:47:54 +00001491
1492 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001493 // We didn't get to the end of the string. This means the component names
1494 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001495 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1496 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001497 return QualType();
1498 }
Nate Begeman1486b502009-01-18 01:47:54 +00001499
1500 // Ensure no component accessor exceeds the width of the vector type it
1501 // operates on.
1502 if (!HalvingSwizzle) {
1503 compStr = CompName.getName();
1504
1505 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001506 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001507
1508 while (*compStr) {
1509 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1510 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1511 << baseType << SourceRange(CompLoc);
1512 return QualType();
1513 }
1514 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001515 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001516
Nate Begeman1486b502009-01-18 01:47:54 +00001517 // If this is a halving swizzle, verify that the base type has an even
1518 // number of elements.
1519 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001520 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001521 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001522 return QualType();
1523 }
1524
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001525 // The component accessor looks fine - now we need to compute the actual type.
1526 // The vector type is implied by the component accessor. For example,
1527 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001528 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001529 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001530 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1531 : CompName.getLength();
1532 if (HexSwizzle)
1533 CompSize--;
1534
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001535 if (CompSize == 1)
1536 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001537
Nate Begemanaf6ed502008-04-18 23:10:10 +00001538 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001539 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001540 // diagostics look bad. We want extended vector types to appear built-in.
1541 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1542 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1543 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001544 }
1545 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001546}
1547
Chris Lattner2cb744b2009-02-15 22:43:40 +00001548
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001549/// constructSetterName - Return the setter name for the given
1550/// identifier, i.e. "set" + Name where the initial character of Name
1551/// has been capitalized.
1552// FIXME: Merge with same routine in Parser. But where should this
1553// live?
1554static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1555 const IdentifierInfo *Name) {
1556 llvm::SmallString<100> SelectorName;
1557 SelectorName = "set";
1558 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1559 SelectorName[3] = toupper(SelectorName[3]);
1560 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1561}
1562
Sebastian Redl8b769972009-01-19 00:08:26 +00001563Action::OwningExprResult
1564Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1565 tok::TokenKind OpKind, SourceLocation MemberLoc,
1566 IdentifierInfo &Member) {
1567 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001568 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001569
1570 // Perform default conversions.
1571 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001572
Steve Naroff2cb66382007-07-26 03:11:44 +00001573 QualType BaseType = BaseExpr->getType();
1574 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001575
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001576 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1577 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001578 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001579 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001580 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001581 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001582 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1583 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001584 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001585 return ExprError(Diag(MemberLoc,
1586 diag::err_typecheck_member_reference_arrow)
1587 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001588 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001589
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001590 // Handle field access to simple records. This also handles access to fields
1591 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001592 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001593 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001594 if (DiagnoseIncompleteType(OpLoc, BaseType,
1595 diag::err_typecheck_incomplete_tag,
1596 BaseExpr->getSourceRange()))
1597 return ExprError();
1598
Steve Naroff2cb66382007-07-26 03:11:44 +00001599 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001600 // FIXME: Qualified name lookup for C++ is a bit more complicated
1601 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001602 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001603 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001604 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001605
Douglas Gregor09be81b2009-02-04 17:27:36 +00001606 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001607 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001608 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1609 << &Member << BaseExpr->getSourceRange());
1610 else if (Result.isAmbiguous()) {
1611 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1612 MemberLoc, BaseExpr->getSourceRange());
1613 return ExprError();
1614 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001615 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001616
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001617 // If the decl being referenced had an error, return an error for this
1618 // sub-expr without emitting another error, in order to avoid cascading
1619 // error cases.
1620 if (MemberDecl->isInvalidDecl())
1621 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001622
1623 // Check if referencing a field with __attribute__((deprecated)).
1624 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001625
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001626 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001627 // We may have found a field within an anonymous union or struct
1628 // (C++ [class.union]).
1629 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001630 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001631 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001632
Douglas Gregor82d44772008-12-20 23:49:58 +00001633 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1634 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001635 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001636 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1637 MemberType = Ref->getPointeeType();
1638 else {
1639 unsigned combinedQualifiers =
1640 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001641 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001642 combinedQualifiers &= ~QualType::Const;
1643 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1644 }
Eli Friedman76b49832008-02-06 22:48:16 +00001645
Steve Naroff774e4152009-01-21 00:14:39 +00001646 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1647 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001648 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001649 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001650 Var, MemberLoc,
1651 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001652 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001653 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1654 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001656 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001657 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001658 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001659 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001660 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001661 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001662 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001663 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1664 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001665
Douglas Gregor82d44772008-12-20 23:49:58 +00001666 // We found a declaration kind that we didn't expect. This is a
1667 // generic error message that tells the user that she can't refer
1668 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001669 return ExprError(Diag(MemberLoc,
1670 diag::err_typecheck_member_reference_unknown)
1671 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001672 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001673
Chris Lattnere9d71612008-07-21 04:59:05 +00001674 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1675 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001676 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001677 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001678 // If the decl being referenced had an error, return an error for this
1679 // sub-expr without emitting another error, in order to avoid cascading
1680 // error cases.
1681 if (IV->isInvalidDecl())
1682 return ExprError();
1683
Chris Lattner2a3bef92009-02-16 17:19:12 +00001684 // Check if referencing a field with __attribute__((deprecated)).
1685 DiagnoseUseOfDeprecatedDecl(IV, MemberLoc);
1686
Steve Naroff774e4152009-01-21 00:14:39 +00001687 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1688 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001689 OpKind == tok::arrow);
1690 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001691 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001692 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001693 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1694 << IFTy->getDecl()->getDeclName() << &Member
1695 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001696 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001697
Chris Lattnere9d71612008-07-21 04:59:05 +00001698 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1699 // pointer to a (potentially qualified) interface type.
1700 const PointerType *PTy;
1701 const ObjCInterfaceType *IFTy;
1702 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1703 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1704 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001705
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001706 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001707 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1708 // Check if referencing a property with __attribute__((deprecated)).
1709 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1710
Steve Naroff774e4152009-01-21 00:14:39 +00001711 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001712 MemberLoc, BaseExpr));
1713 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001714
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001715 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001716 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1717 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001718 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1719 // Check if referencing a property with __attribute__((deprecated)).
1720 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1721
Steve Naroff774e4152009-01-21 00:14:39 +00001722 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001723 MemberLoc, BaseExpr));
1724 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001725
1726 // If that failed, look for an "implicit" property by seeing if the nullary
1727 // selector is implemented.
1728
1729 // FIXME: The logic for looking up nullary and unary selectors should be
1730 // shared with the code in ActOnInstanceMessage.
1731
1732 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1733 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001734
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001735 // If this reference is in an @implementation, check for 'private' methods.
1736 if (!Getter)
1737 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1738 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1739 if (ObjCImplementationDecl *ImpDecl =
1740 ObjCImplementations[ClassDecl->getIdentifier()])
1741 Getter = ImpDecl->getInstanceMethod(Sel);
1742
Steve Naroff04151f32008-10-22 19:16:27 +00001743 // Look through local category implementations associated with the class.
1744 if (!Getter) {
1745 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1746 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1747 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1748 }
1749 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001750 if (Getter) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001751 // Check if referencing a property with __attribute__((deprecated)).
1752 DiagnoseUseOfDeprecatedDecl(Getter, MemberLoc);
1753
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001754 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001755 // will look for the matching setter, in case it is needed.
1756 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1757 &Member);
1758 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1759 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1760 if (!Setter) {
1761 // If this reference is in an @implementation, also check for 'private'
1762 // methods.
1763 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1764 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1765 if (ObjCImplementationDecl *ImpDecl =
1766 ObjCImplementations[ClassDecl->getIdentifier()])
1767 Setter = ImpDecl->getInstanceMethod(SetterSel);
1768 }
1769 // Look through local category implementations associated with the class.
1770 if (!Setter) {
1771 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1772 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1773 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1774 }
1775 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001776
Chris Lattner51f6fb32009-02-16 18:35:08 +00001777 if (Setter)
1778 // Check if referencing a property with __attribute__((deprecated)).
1779 DiagnoseUseOfDeprecatedDecl(Setter, MemberLoc);
1780
1781
Sebastian Redl8b769972009-01-19 00:08:26 +00001782 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001783 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1784 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001785 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001786
1787 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1788 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001789 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001790 // Handle properties on qualified "id" protocols.
1791 const ObjCQualifiedIdType *QIdTy;
1792 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1793 // Check protocols on qualified interfaces.
1794 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001795 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001796 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1797 // Check if referencing a property with __attribute__((deprecated)).
1798 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1799
Steve Naroff774e4152009-01-21 00:14:39 +00001800 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001801 MemberLoc, BaseExpr));
1802 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001803 // Also must look for a getter name which uses property syntax.
1804 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1805 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001806 // Check if referencing a property with __attribute__((deprecated)).
1807 DiagnoseUseOfDeprecatedDecl(OMD, MemberLoc);
1808
Steve Naroff774e4152009-01-21 00:14:39 +00001809 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1810 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001811 }
1812 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001813
1814 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1815 << &Member << BaseType);
1816 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001817 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001818 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001819 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1820 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001821 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001822 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1823 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001824 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001825
1826 return ExprError(Diag(MemberLoc,
1827 diag::err_typecheck_member_reference_struct_union)
1828 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001829}
1830
Douglas Gregor3257fb52008-12-22 05:46:06 +00001831/// ConvertArgumentsForCall - Converts the arguments specified in
1832/// Args/NumArgs to the parameter types of the function FDecl with
1833/// function prototype Proto. Call is the call expression itself, and
1834/// Fn is the function expression. For a C++ member function, this
1835/// routine does not attempt to convert the object argument. Returns
1836/// true if the call is ill-formed.
1837bool
1838Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1839 FunctionDecl *FDecl,
1840 const FunctionTypeProto *Proto,
1841 Expr **Args, unsigned NumArgs,
1842 SourceLocation RParenLoc) {
1843 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1844 // assignment, to the types of the corresponding parameter, ...
1845 unsigned NumArgsInProto = Proto->getNumArgs();
1846 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001847 bool Invalid = false;
1848
Douglas Gregor3257fb52008-12-22 05:46:06 +00001849 // If too few arguments are available (and we don't have default
1850 // arguments for the remaining parameters), don't make the call.
1851 if (NumArgs < NumArgsInProto) {
1852 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1853 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1854 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1855 // Use default arguments for missing arguments
1856 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001857 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001858 }
1859
1860 // If too many are passed and not variadic, error on the extras and drop
1861 // them.
1862 if (NumArgs > NumArgsInProto) {
1863 if (!Proto->isVariadic()) {
1864 Diag(Args[NumArgsInProto]->getLocStart(),
1865 diag::err_typecheck_call_too_many_args)
1866 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1867 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1868 Args[NumArgs-1]->getLocEnd());
1869 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001870 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001871 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001872 }
1873 NumArgsToCheck = NumArgsInProto;
1874 }
1875
1876 // Continue to check argument types (even if we have too few/many args).
1877 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1878 QualType ProtoArgType = Proto->getArgType(i);
1879
1880 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001881 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001882 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001883
1884 // Pass the argument.
1885 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1886 return true;
1887 } else
1888 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001889 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001890 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001891
Douglas Gregor3257fb52008-12-22 05:46:06 +00001892 Call->setArg(i, Arg);
1893 }
1894
1895 // If this is a variadic call, handle args passed through "...".
1896 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001897 VariadicCallType CallType = VariadicFunction;
1898 if (Fn->getType()->isBlockPointerType())
1899 CallType = VariadicBlock; // Block
1900 else if (isa<MemberExpr>(Fn))
1901 CallType = VariadicMethod;
1902
Douglas Gregor3257fb52008-12-22 05:46:06 +00001903 // Promote the arguments (C99 6.5.2.2p7).
1904 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1905 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001906 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001907 Call->setArg(i, Arg);
1908 }
1909 }
1910
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001911 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001912}
1913
Steve Naroff87d58b42007-09-16 03:34:24 +00001914/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001915/// This provides the location of the left/right parens and a list of comma
1916/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001917Action::OwningExprResult
1918Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1919 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001920 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001921 unsigned NumArgs = args.size();
1922 Expr *Fn = static_cast<Expr *>(fn.release());
1923 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001924 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001925 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001926 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001927
Douglas Gregor3257fb52008-12-22 05:46:06 +00001928 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001929 // Determine whether this is a dependent call inside a C++ template,
1930 // in which case we won't do any semantic analysis now.
1931 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1932 bool Dependent = false;
1933 if (Fn->isTypeDependent())
1934 Dependent = true;
1935 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1936 Dependent = true;
1937
1938 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001939 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001940 Context.DependentTy, RParenLoc));
1941
1942 // Determine whether this is a call to an object (C++ [over.call.object]).
1943 if (Fn->getType()->isRecordType())
1944 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1945 CommaLocs, RParenLoc));
1946
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001947 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001948 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1949 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1950 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001951 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1952 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001953 }
1954
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001955 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001956 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001957 Expr *FnExpr = Fn;
1958 bool ADL = true;
1959 while (true) {
1960 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1961 FnExpr = IcExpr->getSubExpr();
1962 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001963 // Parentheses around a function disable ADL
1964 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001965 ADL = false;
1966 FnExpr = PExpr->getSubExpr();
1967 } else if (isa<UnaryOperator>(FnExpr) &&
1968 cast<UnaryOperator>(FnExpr)->getOpcode()
1969 == UnaryOperator::AddrOf) {
1970 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001971 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1972 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1973 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1974 break;
1975 } else if (UnresolvedFunctionNameExpr *DepName
1976 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1977 UnqualifiedName = DepName->getName();
1978 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001979 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001980 // Any kind of name that does not refer to a declaration (or
1981 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1982 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001983 break;
1984 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001985 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001986
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001987 OverloadedFunctionDecl *Ovl = 0;
1988 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001989 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001990 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1991 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001992
Douglas Gregorfcb19192009-02-11 23:02:49 +00001993 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001994 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001995 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001996 ADL = false;
1997
Douglas Gregorfcb19192009-02-11 23:02:49 +00001998 // We don't perform ADL in C.
1999 if (!getLangOptions().CPlusPlus)
2000 ADL = false;
2001
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002002 if (Ovl || ADL) {
2003 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2004 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002005 NumArgs, CommaLocs, RParenLoc, ADL);
2006 if (!FDecl)
2007 return ExprError();
2008
2009 // Update Fn to refer to the actual function selected.
2010 Expr *NewFn = 0;
2011 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002012 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002013 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2014 QDRExpr->getLocation(),
2015 false, false,
2016 QDRExpr->getSourceRange().getBegin());
2017 else
2018 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2019 Fn->getSourceRange().getBegin());
2020 Fn->Destroy(Context);
2021 Fn = NewFn;
2022 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002023 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002024
2025 // Promote the function operand.
2026 UsualUnaryConversions(Fn);
2027
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002028 // Make the call expr early, before semantic checks. This guarantees cleanup
2029 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00002030 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
2031 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002032 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2033 Args, NumArgs,
2034 Context.BoolTy,
2035 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002036
Steve Naroffd6163f32008-09-05 22:11:13 +00002037 const FunctionType *FuncT;
2038 if (!Fn->getType()->isBlockPointerType()) {
2039 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2040 // have type pointer to function".
2041 const PointerType *PT = Fn->getType()->getAsPointerType();
2042 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002043 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2044 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002045 FuncT = PT->getPointeeType()->getAsFunctionType();
2046 } else { // This is a block call.
2047 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2048 getAsFunctionType();
2049 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002050 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002051 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2052 << Fn->getType() << Fn->getSourceRange());
2053
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002054 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002055 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002056
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002057 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002058 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2059 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002060 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002061 } else {
2062 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002063
Steve Naroffdb65e052007-08-28 23:30:39 +00002064 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002065 for (unsigned i = 0; i != NumArgs; i++) {
2066 Expr *Arg = Args[i];
2067 DefaultArgumentPromotion(Arg);
2068 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002069 }
Chris Lattner4b009652007-07-25 00:24:17 +00002070 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002071
Douglas Gregor3257fb52008-12-22 05:46:06 +00002072 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2073 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002074 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2075 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002076
Chris Lattner2e64c072007-08-10 20:18:51 +00002077 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002078 if (FDecl)
2079 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002080
Sebastian Redl8b769972009-01-19 00:08:26 +00002081 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002082}
2083
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002084Action::OwningExprResult
2085Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2086 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002087 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002088 QualType literalType = QualType::getFromOpaquePtr(Ty);
2089 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002090 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002091 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002092
Eli Friedman8c2173d2008-05-20 05:22:08 +00002093 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002094 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002095 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2096 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002097 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2098 diag::err_typecheck_decl_incomplete_type,
2099 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002100 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002101
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002102 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002103 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002104 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002105
Chris Lattnere5cb5862008-12-04 23:50:19 +00002106 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002107 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002108 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002109 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002110 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002111 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002112 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2113 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002114}
2115
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002116Action::OwningExprResult
2117Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2118 InitListDesignations &Designators,
2119 SourceLocation RBraceLoc) {
2120 unsigned NumInit = initlist.size();
2121 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002122
Steve Naroff0acc9c92007-09-15 18:49:24 +00002123 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002124 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002125
Steve Naroff774e4152009-01-21 00:14:39 +00002126 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002127 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002128 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002129 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002130}
2131
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002132/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002133bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002134 UsualUnaryConversions(castExpr);
2135
2136 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2137 // type needs to be scalar.
2138 if (castType->isVoidType()) {
2139 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002140 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2141 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002142 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002143 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2144 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2145 (castType->isStructureType() || castType->isUnionType())) {
2146 // GCC struct/union extension: allow cast to self.
2147 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2148 << castType << castExpr->getSourceRange();
2149 } else if (castType->isUnionType()) {
2150 // GCC cast to union extension
2151 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2152 RecordDecl::field_iterator Field, FieldEnd;
2153 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2154 Field != FieldEnd; ++Field) {
2155 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2156 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2157 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2158 << castExpr->getSourceRange();
2159 break;
2160 }
2161 }
2162 if (Field == FieldEnd)
2163 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2164 << castExpr->getType() << castExpr->getSourceRange();
2165 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002166 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002167 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002168 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002169 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002170 } else if (!castExpr->getType()->isScalarType() &&
2171 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002172 return Diag(castExpr->getLocStart(),
2173 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002174 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002175 } else if (castExpr->getType()->isVectorType()) {
2176 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2177 return true;
2178 } else if (castType->isVectorType()) {
2179 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2180 return true;
2181 }
2182 return false;
2183}
2184
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002185bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002186 assert(VectorTy->isVectorType() && "Not a vector type!");
2187
2188 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002189 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002190 return Diag(R.getBegin(),
2191 Ty->isVectorType() ?
2192 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002193 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002194 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002195 } else
2196 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002197 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002198 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002199
2200 return false;
2201}
2202
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002203Action::OwningExprResult
2204Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2205 SourceLocation RParenLoc, ExprArg Op) {
2206 assert((Ty != 0) && (Op.get() != 0) &&
2207 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002208
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002209 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002210 QualType castType = QualType::getFromOpaquePtr(Ty);
2211
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002212 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002213 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002214 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002215 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002216}
2217
Chris Lattner98a425c2007-11-26 01:40:58 +00002218/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2219/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002220inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2221 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2222 UsualUnaryConversions(cond);
2223 UsualUnaryConversions(lex);
2224 UsualUnaryConversions(rex);
2225 QualType condT = cond->getType();
2226 QualType lexT = lex->getType();
2227 QualType rexT = rex->getType();
2228
2229 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002230 if (!cond->isTypeDependent()) {
2231 if (!condT->isScalarType()) { // C99 6.5.15p2
2232 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2233 return QualType();
2234 }
Chris Lattner4b009652007-07-25 00:24:17 +00002235 }
Chris Lattner992ae932008-01-06 22:42:25 +00002236
2237 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002238 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2239 return Context.DependentTy;
2240
Chris Lattner992ae932008-01-06 22:42:25 +00002241 // If both operands have arithmetic type, do the usual arithmetic conversions
2242 // to find a common type: C99 6.5.15p3,5.
2243 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002244 UsualArithmeticConversions(lex, rex);
2245 return lex->getType();
2246 }
Chris Lattner992ae932008-01-06 22:42:25 +00002247
2248 // If both operands are the same structure or union type, the result is that
2249 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002250 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002251 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002252 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002253 // "If both the operands have structure or union type, the result has
2254 // that type." This implies that CV qualifiers are dropped.
2255 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002256 }
Chris Lattner992ae932008-01-06 22:42:25 +00002257
2258 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002259 // The following || allows only one side to be void (a GCC-ism).
2260 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002261 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002262 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2263 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002264 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002265 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2266 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002267 ImpCastExprToType(lex, Context.VoidTy);
2268 ImpCastExprToType(rex, Context.VoidTy);
2269 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002270 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002271 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2272 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002273 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2274 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002275 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002276 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002277 return lexT;
2278 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002279 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2280 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002281 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002282 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002283 return rexT;
2284 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002285 // Handle the case where both operands are pointers before we handle null
2286 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002287 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2288 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2289 // get the "pointed to" types
2290 QualType lhptee = LHSPT->getPointeeType();
2291 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002292
Chris Lattner71225142007-07-31 21:27:01 +00002293 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2294 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002295 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002296 // Figure out necessary qualifiers (C99 6.5.15p6)
2297 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002298 QualType destType = Context.getPointerType(destPointee);
2299 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2300 ImpCastExprToType(rex, destType); // promote to void*
2301 return destType;
2302 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002303 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002304 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002305 QualType destType = Context.getPointerType(destPointee);
2306 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2307 ImpCastExprToType(rex, destType); // promote to void*
2308 return destType;
2309 }
Chris Lattner4b009652007-07-25 00:24:17 +00002310
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002311 QualType compositeType = lexT;
2312
2313 // If either type is an Objective-C object type then check
2314 // compatibility according to Objective-C.
2315 if (Context.isObjCObjectPointerType(lexT) ||
2316 Context.isObjCObjectPointerType(rexT)) {
2317 // If both operands are interfaces and either operand can be
2318 // assigned to the other, use that type as the composite
2319 // type. This allows
2320 // xxx ? (A*) a : (B*) b
2321 // where B is a subclass of A.
2322 //
2323 // Additionally, as for assignment, if either type is 'id'
2324 // allow silent coercion. Finally, if the types are
2325 // incompatible then make sure to use 'id' as the composite
2326 // type so the result is acceptable for sending messages to.
2327
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002328 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2329 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002330 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2331 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2332 if (LHSIface && RHSIface &&
2333 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2334 compositeType = lexT;
2335 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002336 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002337 compositeType = rexT;
Steve Naroff17c03822009-02-12 17:52:19 +00002338 } else if (Context.isObjCIdStructType(lhptee) ||
2339 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002340 compositeType = Context.getObjCIdType();
2341 } else {
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002342 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2343 << lexT << rexT
2344 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002345 QualType incompatTy = Context.getObjCIdType();
2346 ImpCastExprToType(lex, incompatTy);
2347 ImpCastExprToType(rex, incompatTy);
2348 return incompatTy;
2349 }
2350 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2351 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002352 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002353 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002354 // In this situation, we assume void* type. No especially good
2355 // reason, but this is what gcc does, and we do have to pick
2356 // to get a consistent AST.
2357 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002358 ImpCastExprToType(lex, incompatTy);
2359 ImpCastExprToType(rex, incompatTy);
2360 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002361 }
2362 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002363 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2364 // differently qualified versions of compatible types, the result type is
2365 // a pointer to an appropriately qualified version of the *composite*
2366 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002367 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002368 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002369 ImpCastExprToType(lex, compositeType);
2370 ImpCastExprToType(rex, compositeType);
2371 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002372 }
Chris Lattner4b009652007-07-25 00:24:17 +00002373 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002374 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2375 // evaluates to "struct objc_object *" (and is handled above when comparing
2376 // id with statically typed objects).
2377 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2378 // GCC allows qualified id and any Objective-C type to devolve to
2379 // id. Currently localizing to here until clear this should be
2380 // part of ObjCQualifiedIdTypesAreCompatible.
2381 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2382 (lexT->isObjCQualifiedIdType() &&
2383 Context.isObjCObjectPointerType(rexT)) ||
2384 (rexT->isObjCQualifiedIdType() &&
2385 Context.isObjCObjectPointerType(lexT))) {
2386 // FIXME: This is not the correct composite type. This only
2387 // happens to work because id can more or less be used anywhere,
2388 // however this may change the type of method sends.
2389 // FIXME: gcc adds some type-checking of the arguments and emits
2390 // (confusing) incompatible comparison warnings in some
2391 // cases. Investigate.
2392 QualType compositeType = Context.getObjCIdType();
2393 ImpCastExprToType(lex, compositeType);
2394 ImpCastExprToType(rex, compositeType);
2395 return compositeType;
2396 }
2397 }
2398
Steve Naroff3eac7692008-09-10 19:17:48 +00002399 // Selection between block pointer types is ok as long as they are the same.
2400 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2401 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2402 return lexT;
2403
Chris Lattner992ae932008-01-06 22:42:25 +00002404 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002405 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002406 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002407 return QualType();
2408}
2409
Steve Naroff87d58b42007-09-16 03:34:24 +00002410/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002411/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002412Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2413 SourceLocation ColonLoc,
2414 ExprArg Cond, ExprArg LHS,
2415 ExprArg RHS) {
2416 Expr *CondExpr = (Expr *) Cond.get();
2417 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002418
2419 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2420 // was the condition.
2421 bool isLHSNull = LHSExpr == 0;
2422 if (isLHSNull)
2423 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002424
2425 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002426 RHSExpr, QuestionLoc);
2427 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002428 return ExprError();
2429
2430 Cond.release();
2431 LHS.release();
2432 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002433 return Owned(new (Context) ConditionalOperator(CondExpr,
2434 isLHSNull ? 0 : LHSExpr,
2435 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002436}
2437
Chris Lattner4b009652007-07-25 00:24:17 +00002438
2439// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2440// being closely modeled after the C99 spec:-). The odd characteristic of this
2441// routine is it effectively iqnores the qualifiers on the top level pointee.
2442// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2443// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002444Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002445Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2446 QualType lhptee, rhptee;
2447
2448 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002449 lhptee = lhsType->getAsPointerType()->getPointeeType();
2450 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002451
2452 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002453 lhptee = Context.getCanonicalType(lhptee);
2454 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002455
Chris Lattner005ed752008-01-04 18:04:52 +00002456 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002457
2458 // C99 6.5.16.1p1: This following citation is common to constraints
2459 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2460 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002461 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002462 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002463 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002464
2465 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2466 // incomplete type and the other is a pointer to a qualified or unqualified
2467 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002468 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002469 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002470 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002471
2472 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002473 assert(rhptee->isFunctionType());
2474 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002475 }
2476
2477 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002478 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002479 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002480
2481 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002482 assert(lhptee->isFunctionType());
2483 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002484 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002485
2486 // Check for ObjC interfaces
2487 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2488 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2489 if (LHSIface && RHSIface &&
2490 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2491 return ConvTy;
2492
2493 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002494 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002495 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002496 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002497 return ConvTy;
2498
Chris Lattner4b009652007-07-25 00:24:17 +00002499 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2500 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002501 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2502 rhptee.getUnqualifiedType()))
2503 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002504 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002505}
2506
Steve Naroff3454b6c2008-09-04 15:10:53 +00002507/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2508/// block pointer types are compatible or whether a block and normal pointer
2509/// are compatible. It is more restrict than comparing two function pointer
2510// types.
2511Sema::AssignConvertType
2512Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2513 QualType rhsType) {
2514 QualType lhptee, rhptee;
2515
2516 // get the "pointed to" type (ignoring qualifiers at the top level)
2517 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2518 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2519
2520 // make sure we operate on the canonical type
2521 lhptee = Context.getCanonicalType(lhptee);
2522 rhptee = Context.getCanonicalType(rhptee);
2523
2524 AssignConvertType ConvTy = Compatible;
2525
2526 // For blocks we enforce that qualifiers are identical.
2527 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2528 ConvTy = CompatiblePointerDiscardsQualifiers;
2529
2530 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2531 return IncompatibleBlockPointer;
2532 return ConvTy;
2533}
2534
Chris Lattner4b009652007-07-25 00:24:17 +00002535/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2536/// has code to accommodate several GCC extensions when type checking
2537/// pointers. Here are some objectionable examples that GCC considers warnings:
2538///
2539/// int a, *pint;
2540/// short *pshort;
2541/// struct foo *pfoo;
2542///
2543/// pint = pshort; // warning: assignment from incompatible pointer type
2544/// a = pint; // warning: assignment makes integer from pointer without a cast
2545/// pint = a; // warning: assignment makes pointer from integer without a cast
2546/// pint = pfoo; // warning: assignment from incompatible pointer type
2547///
2548/// As a result, the code for dealing with pointers is more complex than the
2549/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002550///
Chris Lattner005ed752008-01-04 18:04:52 +00002551Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002552Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002553 // Get canonical types. We're not formatting these types, just comparing
2554 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002555 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2556 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002557
2558 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002559 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002560
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002561 // If the left-hand side is a reference type, then we are in a
2562 // (rare!) case where we've allowed the use of references in C,
2563 // e.g., as a parameter type in a built-in function. In this case,
2564 // just make sure that the type referenced is compatible with the
2565 // right-hand side type. The caller is responsible for adjusting
2566 // lhsType so that the resulting expression does not have reference
2567 // type.
2568 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2569 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002570 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002571 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002572 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002573
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002574 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2575 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002576 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002577 // Relax integer conversions like we do for pointers below.
2578 if (rhsType->isIntegerType())
2579 return IntToPointer;
2580 if (lhsType->isIntegerType())
2581 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002582 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002583 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002584
Nate Begemanc5f0f652008-07-14 18:02:46 +00002585 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002586 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002587 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2588 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002589 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002590
Nate Begemanc5f0f652008-07-14 18:02:46 +00002591 // If we are allowing lax vector conversions, and LHS and RHS are both
2592 // vectors, the total size only needs to be the same. This is a bitcast;
2593 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002594 if (getLangOptions().LaxVectorConversions &&
2595 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002596 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002597 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002598 }
2599 return Incompatible;
2600 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002601
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002602 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002603 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002604
Chris Lattner390564e2008-04-07 06:49:41 +00002605 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002606 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002607 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002608
Chris Lattner390564e2008-04-07 06:49:41 +00002609 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002610 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002611
Steve Naroffa982c712008-09-29 18:10:17 +00002612 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002613 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002614 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002615
2616 // Treat block pointers as objects.
2617 if (getLangOptions().ObjC1 &&
2618 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2619 return Compatible;
2620 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002621 return Incompatible;
2622 }
2623
2624 if (isa<BlockPointerType>(lhsType)) {
2625 if (rhsType->isIntegerType())
2626 return IntToPointer;
2627
Steve Naroffa982c712008-09-29 18:10:17 +00002628 // Treat block pointers as objects.
2629 if (getLangOptions().ObjC1 &&
2630 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2631 return Compatible;
2632
Steve Naroff3454b6c2008-09-04 15:10:53 +00002633 if (rhsType->isBlockPointerType())
2634 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2635
2636 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2637 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002638 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002639 }
Chris Lattner1853da22008-01-04 23:18:45 +00002640 return Incompatible;
2641 }
2642
Chris Lattner390564e2008-04-07 06:49:41 +00002643 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002644 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002645 if (lhsType == Context.BoolTy)
2646 return Compatible;
2647
2648 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002649 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002650
Chris Lattner390564e2008-04-07 06:49:41 +00002651 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002652 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002653
2654 if (isa<BlockPointerType>(lhsType) &&
2655 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002656 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002657 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002658 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002659
Chris Lattner1853da22008-01-04 23:18:45 +00002660 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002661 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002662 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002663 }
2664 return Incompatible;
2665}
2666
Chris Lattner005ed752008-01-04 18:04:52 +00002667Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002668Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002669 if (getLangOptions().CPlusPlus) {
2670 if (!lhsType->isRecordType()) {
2671 // C++ 5.17p3: If the left operand is not of class type, the
2672 // expression is implicitly converted (C++ 4) to the
2673 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002674 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2675 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002676 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002677 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002678 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002679 }
2680
2681 // FIXME: Currently, we fall through and treat C++ classes like C
2682 // structures.
2683 }
2684
Steve Naroffcdee22d2007-11-27 17:58:44 +00002685 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2686 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002687 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2688 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002689 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002690 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002691 return Compatible;
2692 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002693
2694 // We don't allow conversion of non-null-pointer constants to integers.
2695 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2696 return IntToBlockPointer;
2697
Chris Lattner5f505bf2007-10-16 02:55:40 +00002698 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002699 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002700 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002701 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002702 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002703 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002704 if (!lhsType->isReferenceType())
2705 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002706
Chris Lattner005ed752008-01-04 18:04:52 +00002707 Sema::AssignConvertType result =
2708 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002709
2710 // C99 6.5.16.1p2: The value of the right operand is converted to the
2711 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002712 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2713 // so that we can use references in built-in functions even in C.
2714 // The getNonReferenceType() call makes sure that the resulting expression
2715 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002716 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002717 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002718 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002719}
2720
Chris Lattner005ed752008-01-04 18:04:52 +00002721Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002722Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2723 return CheckAssignmentConstraints(lhsType, rhsType);
2724}
2725
Chris Lattner1eafdea2008-11-18 01:30:42 +00002726QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002727 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002728 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002729 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002730 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002731}
2732
Chris Lattner1eafdea2008-11-18 01:30:42 +00002733inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002734 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002735 // For conversion purposes, we ignore any qualifiers.
2736 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002737 QualType lhsType =
2738 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2739 QualType rhsType =
2740 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002741
Nate Begemanc5f0f652008-07-14 18:02:46 +00002742 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002743 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002744 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002745
Nate Begemanc5f0f652008-07-14 18:02:46 +00002746 // Handle the case of a vector & extvector type of the same size and element
2747 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002748 if (getLangOptions().LaxVectorConversions) {
2749 // FIXME: Should we warn here?
2750 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002751 if (const VectorType *RV = rhsType->getAsVectorType())
2752 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002753 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002754 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002755 }
2756 }
2757 }
2758
Nate Begemanc5f0f652008-07-14 18:02:46 +00002759 // If the lhs is an extended vector and the rhs is a scalar of the same type
2760 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002761 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002762 QualType eltType = V->getElementType();
2763
2764 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2765 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2766 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002767 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002768 return lhsType;
2769 }
2770 }
2771
Nate Begemanc5f0f652008-07-14 18:02:46 +00002772 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002773 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002774 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002775 QualType eltType = V->getElementType();
2776
2777 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2778 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2779 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002780 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002781 return rhsType;
2782 }
2783 }
2784
Chris Lattner4b009652007-07-25 00:24:17 +00002785 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002786 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002787 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002788 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002789 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002790}
2791
Chris Lattner4b009652007-07-25 00:24:17 +00002792inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002793 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002794{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002795 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002796 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002797
Steve Naroff8f708362007-08-24 19:07:16 +00002798 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002799
Chris Lattner4b009652007-07-25 00:24:17 +00002800 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002801 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002802 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002803}
2804
2805inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002806 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002807{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002808 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2809 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2810 return CheckVectorOperands(Loc, lex, rex);
2811 return InvalidOperands(Loc, lex, rex);
2812 }
Chris Lattner4b009652007-07-25 00:24:17 +00002813
Steve Naroff8f708362007-08-24 19:07:16 +00002814 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002815
Chris Lattner4b009652007-07-25 00:24:17 +00002816 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002817 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002818 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002819}
2820
2821inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002822 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002823{
2824 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002825 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002826
Steve Naroff8f708362007-08-24 19:07:16 +00002827 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002828
Chris Lattner4b009652007-07-25 00:24:17 +00002829 // handle the common case first (both operands are arithmetic).
2830 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002831 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002832
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002833 // Put any potential pointer into PExp
2834 Expr* PExp = lex, *IExp = rex;
2835 if (IExp->getType()->isPointerType())
2836 std::swap(PExp, IExp);
2837
2838 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2839 if (IExp->getType()->isIntegerType()) {
2840 // Check for arithmetic on pointers to incomplete types
2841 if (!PTy->getPointeeType()->isObjectType()) {
2842 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002843 if (getLangOptions().CPlusPlus) {
2844 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2845 << lex->getSourceRange() << rex->getSourceRange();
2846 return QualType();
2847 }
2848
2849 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002850 Diag(Loc, diag::ext_gnu_void_ptr)
2851 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002852 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002853 if (getLangOptions().CPlusPlus) {
2854 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2855 << lex->getType() << lex->getSourceRange();
2856 return QualType();
2857 }
2858
2859 // GNU extension: arithmetic on pointer to function
2860 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002861 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002862 } else {
2863 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2864 diag::err_typecheck_arithmetic_incomplete_type,
2865 lex->getSourceRange(), SourceRange(),
2866 lex->getType());
2867 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002868 }
2869 }
2870 return PExp->getType();
2871 }
2872 }
2873
Chris Lattner1eafdea2008-11-18 01:30:42 +00002874 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002875}
2876
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002877// C99 6.5.6
2878QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002879 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002880 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002881 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002882
Steve Naroff8f708362007-08-24 19:07:16 +00002883 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002884
Chris Lattnerf6da2912007-12-09 21:53:25 +00002885 // Enforce type constraints: C99 6.5.6p3.
2886
2887 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002888 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002889 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002890
2891 // Either ptr - int or ptr - ptr.
2892 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002893 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002894
Chris Lattnerf6da2912007-12-09 21:53:25 +00002895 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002896 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002897 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002898 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002899 Diag(Loc, diag::ext_gnu_void_ptr)
2900 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002901 } else if (lpointee->isFunctionType()) {
2902 if (getLangOptions().CPlusPlus) {
2903 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2904 << lex->getType() << lex->getSourceRange();
2905 return QualType();
2906 }
2907
2908 // GNU extension: arithmetic on pointer to function
2909 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2910 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002911 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002912 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002913 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002914 return QualType();
2915 }
2916 }
2917
2918 // The result type of a pointer-int computation is the pointer type.
2919 if (rex->getType()->isIntegerType())
2920 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002921
Chris Lattnerf6da2912007-12-09 21:53:25 +00002922 // Handle pointer-pointer subtractions.
2923 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002924 QualType rpointee = RHSPTy->getPointeeType();
2925
Chris Lattnerf6da2912007-12-09 21:53:25 +00002926 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002927 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002928 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002929 if (rpointee->isVoidType()) {
2930 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002931 Diag(Loc, diag::ext_gnu_void_ptr)
2932 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002933 } else if (rpointee->isFunctionType()) {
2934 if (getLangOptions().CPlusPlus) {
2935 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2936 << rex->getType() << rex->getSourceRange();
2937 return QualType();
2938 }
2939
2940 // GNU extension: arithmetic on pointer to function
2941 if (!lpointee->isFunctionType())
2942 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2943 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002944 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002945 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002946 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002947 return QualType();
2948 }
2949 }
2950
2951 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002952 if (!Context.typesAreCompatible(
2953 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2954 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002955 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002956 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002957 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002958 return QualType();
2959 }
2960
2961 return Context.getPointerDiffType();
2962 }
2963 }
2964
Chris Lattner1eafdea2008-11-18 01:30:42 +00002965 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002966}
2967
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002968// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002969QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002970 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002971 // C99 6.5.7p2: Each of the operands shall have integer type.
2972 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002973 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002974
Chris Lattner2c8bff72007-12-12 05:47:28 +00002975 // Shifts don't perform usual arithmetic conversions, they just do integer
2976 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002977 if (!isCompAssign)
2978 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002979 UsualUnaryConversions(rex);
2980
2981 // "The type of the result is that of the promoted left operand."
2982 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002983}
2984
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002985// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002986QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002987 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002988 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002989 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002990
Chris Lattner254f3bc2007-08-26 01:18:55 +00002991 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002992 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2993 UsualArithmeticConversions(lex, rex);
2994 else {
2995 UsualUnaryConversions(lex);
2996 UsualUnaryConversions(rex);
2997 }
Chris Lattner4b009652007-07-25 00:24:17 +00002998 QualType lType = lex->getType();
2999 QualType rType = rex->getType();
3000
Ted Kremenek486509e2007-10-29 17:13:39 +00003001 // For non-floating point types, check for self-comparisons of the form
3002 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3003 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003004 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003005 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3006 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003007 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003008 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003009 }
3010
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003011 // The result of comparisons is 'bool' in C++, 'int' in C.
3012 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3013
Chris Lattner254f3bc2007-08-26 01:18:55 +00003014 if (isRelational) {
3015 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003016 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003017 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003018 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003019 if (lType->isFloatingType()) {
3020 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003021 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003022 }
3023
Chris Lattner254f3bc2007-08-26 01:18:55 +00003024 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003025 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003026 }
Chris Lattner4b009652007-07-25 00:24:17 +00003027
Chris Lattner22be8422007-08-26 01:10:14 +00003028 bool LHSIsNull = lex->isNullPointerConstant(Context);
3029 bool RHSIsNull = rex->isNullPointerConstant(Context);
3030
Chris Lattner254f3bc2007-08-26 01:18:55 +00003031 // All of the following pointer related warnings are GCC extensions, except
3032 // when handling null pointer constants. One day, we can consider making them
3033 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003034 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003035 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003036 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003037 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003038 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003039
Steve Naroff3b435622007-11-13 14:57:38 +00003040 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003041 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3042 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003043 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003044 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003045 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003046 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003047 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003048 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003049 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003050 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003051 // Handle block pointer types.
3052 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3053 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3054 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3055
3056 if (!LHSIsNull && !RHSIsNull &&
3057 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003058 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003059 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003060 }
3061 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003062 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003063 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003064 // Allow block pointers to be compared with null pointer constants.
3065 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3066 (lType->isPointerType() && rType->isBlockPointerType())) {
3067 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003068 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003069 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003070 }
3071 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003072 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003073 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003074
Steve Naroff936c4362008-06-03 14:04:54 +00003075 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003076 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003077 const PointerType *LPT = lType->getAsPointerType();
3078 const PointerType *RPT = rType->getAsPointerType();
3079 bool LPtrToVoid = LPT ?
3080 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3081 bool RPtrToVoid = RPT ?
3082 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3083
3084 if (!LPtrToVoid && !RPtrToVoid &&
3085 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003086 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003087 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003088 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003089 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003090 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003091 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003092 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003093 }
Steve Naroff936c4362008-06-03 14:04:54 +00003094 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3095 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003096 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003097 } else {
3098 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003099 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003100 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003101 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003102 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003103 }
Steve Naroff936c4362008-06-03 14:04:54 +00003104 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003105 }
Steve Naroff936c4362008-06-03 14:04:54 +00003106 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3107 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003108 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003109 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003110 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003111 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003112 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003113 }
Steve Naroff936c4362008-06-03 14:04:54 +00003114 if (lType->isIntegerType() &&
3115 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003116 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003117 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003118 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003119 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003120 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003121 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003122 // Handle block pointers.
3123 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3124 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003125 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003126 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003127 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003128 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003129 }
3130 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3131 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003132 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003133 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003134 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003135 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003136 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003137 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003138}
3139
Nate Begemanc5f0f652008-07-14 18:02:46 +00003140/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3141/// operates on extended vector types. Instead of producing an IntTy result,
3142/// like a scalar comparison, a vector comparison produces a vector of integer
3143/// types.
3144QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003145 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003146 bool isRelational) {
3147 // Check to make sure we're operating on vectors of the same type and width,
3148 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003149 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003150 if (vType.isNull())
3151 return vType;
3152
3153 QualType lType = lex->getType();
3154 QualType rType = rex->getType();
3155
3156 // For non-floating point types, check for self-comparisons of the form
3157 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3158 // often indicate logic errors in the program.
3159 if (!lType->isFloatingType()) {
3160 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3161 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3162 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003163 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003164 }
3165
3166 // Check for comparisons of floating point operands using != and ==.
3167 if (!isRelational && lType->isFloatingType()) {
3168 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003169 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003170 }
3171
3172 // Return the type for the comparison, which is the same as vector type for
3173 // integer vectors, or an integer type of identical size and number of
3174 // elements for floating point vectors.
3175 if (lType->isIntegerType())
3176 return lType;
3177
3178 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003179 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003180 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003181 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003182 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3183 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3184
3185 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3186 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003187 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3188}
3189
Chris Lattner4b009652007-07-25 00:24:17 +00003190inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003191 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003192{
3193 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003194 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003195
Steve Naroff8f708362007-08-24 19:07:16 +00003196 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003197
3198 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003199 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003200 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003201}
3202
3203inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003204 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003205{
3206 UsualUnaryConversions(lex);
3207 UsualUnaryConversions(rex);
3208
Eli Friedmanbea3f842008-05-13 20:16:47 +00003209 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003210 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003211 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003212}
3213
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003214/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3215/// is a read-only property; return true if so. A readonly property expression
3216/// depends on various declarations and thus must be treated specially.
3217///
3218static bool IsReadonlyProperty(Expr *E, Sema &S)
3219{
3220 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3221 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3222 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3223 QualType BaseType = PropExpr->getBase()->getType();
3224 if (const PointerType *PTy = BaseType->getAsPointerType())
3225 if (const ObjCInterfaceType *IFTy =
3226 PTy->getPointeeType()->getAsObjCInterfaceType())
3227 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3228 if (S.isPropertyReadonly(PDecl, IFace))
3229 return true;
3230 }
3231 }
3232 return false;
3233}
3234
Chris Lattner4c2642c2008-11-18 01:22:49 +00003235/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3236/// emit an error and return true. If so, return false.
3237static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003238 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3239 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3240 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003241 if (IsLV == Expr::MLV_Valid)
3242 return false;
3243
3244 unsigned Diag = 0;
3245 bool NeedType = false;
3246 switch (IsLV) { // C99 6.5.16p2
3247 default: assert(0 && "Unknown result from isModifiableLvalue!");
3248 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003249 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003250 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3251 NeedType = true;
3252 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003253 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003254 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3255 NeedType = true;
3256 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003257 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003258 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3259 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003260 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003261 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3262 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003263 case Expr::MLV_IncompleteType:
3264 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003265 return S.DiagnoseIncompleteType(Loc, E->getType(),
3266 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3267 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003268 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003269 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3270 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003271 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003272 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3273 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003274 case Expr::MLV_ReadonlyProperty:
3275 Diag = diag::error_readonly_property_assignment;
3276 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003277 case Expr::MLV_NoSetterProperty:
3278 Diag = diag::error_nosetter_property_assignment;
3279 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003280 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003281
Chris Lattner4c2642c2008-11-18 01:22:49 +00003282 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003283 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003284 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003285 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003286 return true;
3287}
3288
3289
3290
3291// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003292QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3293 SourceLocation Loc,
3294 QualType CompoundType) {
3295 // Verify that LHS is a modifiable lvalue, and emit error if not.
3296 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003297 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003298
3299 QualType LHSType = LHS->getType();
3300 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003301
Chris Lattner005ed752008-01-04 18:04:52 +00003302 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003303 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003304 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003305 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003306 // Special case of NSObject attributes on c-style pointer types.
3307 if (ConvTy == IncompatiblePointer &&
3308 ((Context.isObjCNSObjectType(LHSType) &&
3309 Context.isObjCObjectPointerType(RHSType)) ||
3310 (Context.isObjCNSObjectType(RHSType) &&
3311 Context.isObjCObjectPointerType(LHSType))))
3312 ConvTy = Compatible;
3313
Chris Lattner34c85082008-08-21 18:04:13 +00003314 // If the RHS is a unary plus or minus, check to see if they = and + are
3315 // right next to each other. If so, the user may have typo'd "x =+ 4"
3316 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003317 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003318 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3319 RHSCheck = ICE->getSubExpr();
3320 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3321 if ((UO->getOpcode() == UnaryOperator::Plus ||
3322 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003323 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003324 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003325 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003326 Diag(Loc, diag::warn_not_compound_assign)
3327 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3328 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003329 }
3330 } else {
3331 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003332 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003333 }
Chris Lattner005ed752008-01-04 18:04:52 +00003334
Chris Lattner1eafdea2008-11-18 01:30:42 +00003335 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3336 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003337 return QualType();
3338
Chris Lattner4b009652007-07-25 00:24:17 +00003339 // C99 6.5.16p3: The type of an assignment expression is the type of the
3340 // left operand unless the left operand has qualified type, in which case
3341 // it is the unqualified version of the type of the left operand.
3342 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3343 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003344 // C++ 5.17p1: the type of the assignment expression is that of its left
3345 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003346 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003347}
3348
Chris Lattner1eafdea2008-11-18 01:30:42 +00003349// C99 6.5.17
3350QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3351 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003352
3353 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003354 DefaultFunctionArrayConversion(RHS);
3355 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003356}
3357
3358/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3359/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003360QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3361 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003362 QualType ResType = Op->getType();
3363 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003364
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003365 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3366 // Decrement of bool is not allowed.
3367 if (!isInc) {
3368 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3369 return QualType();
3370 }
3371 // Increment of bool sets it to true, but is deprecated.
3372 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3373 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003374 // OK!
3375 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3376 // C99 6.5.2.4p2, 6.5.6p2
3377 if (PT->getPointeeType()->isObjectType()) {
3378 // Pointer to object is ok!
3379 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003380 if (getLangOptions().CPlusPlus) {
3381 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3382 << Op->getSourceRange();
3383 return QualType();
3384 }
3385
3386 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003387 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003388 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003389 if (getLangOptions().CPlusPlus) {
3390 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3391 << Op->getType() << Op->getSourceRange();
3392 return QualType();
3393 }
3394
3395 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003396 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003397 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003398 } else {
3399 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3400 diag::err_typecheck_arithmetic_incomplete_type,
3401 Op->getSourceRange(), SourceRange(),
3402 ResType);
3403 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003404 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003405 } else if (ResType->isComplexType()) {
3406 // C99 does not support ++/-- on complex types, we allow as an extension.
3407 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003408 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003409 } else {
3410 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003411 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003412 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003413 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003414 // At this point, we know we have a real, complex or pointer type.
3415 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003416 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003417 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003418 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003419}
3420
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003421/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003422/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003423/// where the declaration is needed for type checking. We only need to
3424/// handle cases when the expression references a function designator
3425/// or is an lvalue. Here are some examples:
3426/// - &(x) => x
3427/// - &*****f => f for f a function designator.
3428/// - &s.xx => s
3429/// - &s.zz[1].yy -> s, if zz is an array
3430/// - *(x + 1) -> x, if x is an array
3431/// - &"123"[2] -> 0
3432/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003433static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003434 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003435 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003436 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003437 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003438 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003439 // Fields cannot be declared with a 'register' storage class.
3440 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003441 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003442 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003443 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003444 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003445 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003446
Douglas Gregord2baafd2008-10-21 16:13:35 +00003447 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003448 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003449 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003450 return 0;
3451 else
3452 return VD;
3453 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003454 case Stmt::UnaryOperatorClass: {
3455 UnaryOperator *UO = cast<UnaryOperator>(E);
3456
3457 switch(UO->getOpcode()) {
3458 case UnaryOperator::Deref: {
3459 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003460 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3461 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3462 if (!VD || VD->getType()->isPointerType())
3463 return 0;
3464 return VD;
3465 }
3466 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003467 }
3468 case UnaryOperator::Real:
3469 case UnaryOperator::Imag:
3470 case UnaryOperator::Extension:
3471 return getPrimaryDecl(UO->getSubExpr());
3472 default:
3473 return 0;
3474 }
3475 }
3476 case Stmt::BinaryOperatorClass: {
3477 BinaryOperator *BO = cast<BinaryOperator>(E);
3478
3479 // Handle cases involving pointer arithmetic. The result of an
3480 // Assign or AddAssign is not an lvalue so they can be ignored.
3481
3482 // (x + n) or (n + x) => x
3483 if (BO->getOpcode() == BinaryOperator::Add) {
3484 if (BO->getLHS()->getType()->isPointerType()) {
3485 return getPrimaryDecl(BO->getLHS());
3486 } else if (BO->getRHS()->getType()->isPointerType()) {
3487 return getPrimaryDecl(BO->getRHS());
3488 }
3489 }
3490
3491 return 0;
3492 }
Chris Lattner4b009652007-07-25 00:24:17 +00003493 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003494 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003495 case Stmt::ImplicitCastExprClass:
3496 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003497 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003498 default:
3499 return 0;
3500 }
3501}
3502
3503/// CheckAddressOfOperand - The operand of & must be either a function
3504/// designator or an lvalue designating an object. If it is an lvalue, the
3505/// object cannot be declared with storage class register or be a bit field.
3506/// Note: The usual conversions are *not* applied to the operand of the &
3507/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003508/// In C++, the operand might be an overloaded function name, in which case
3509/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003510QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003511 if (op->isTypeDependent())
3512 return Context.DependentTy;
3513
Steve Naroff9c6c3592008-01-13 17:10:08 +00003514 if (getLangOptions().C99) {
3515 // Implement C99-only parts of addressof rules.
3516 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3517 if (uOp->getOpcode() == UnaryOperator::Deref)
3518 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3519 // (assuming the deref expression is valid).
3520 return uOp->getSubExpr()->getType();
3521 }
3522 // Technically, there should be a check for array subscript
3523 // expressions here, but the result of one is always an lvalue anyway.
3524 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003525 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003526 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003527
Chris Lattner4b009652007-07-25 00:24:17 +00003528 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003529 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3530 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003531 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3532 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003533 return QualType();
3534 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003535 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003536 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3537 if (Field->isBitField()) {
3538 Diag(OpLoc, diag::err_typecheck_address_of)
3539 << "bit-field" << op->getSourceRange();
3540 return QualType();
3541 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003542 }
3543 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003544 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3545 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003546 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003547 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003548 return QualType();
3549 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003550 // We have an lvalue with a decl. Make sure the decl is not declared
3551 // with the register storage-class specifier.
3552 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3553 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003554 Diag(OpLoc, diag::err_typecheck_address_of)
3555 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003556 return QualType();
3557 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003558 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003559 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003560 } else if (isa<FieldDecl>(dcl)) {
3561 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003562 // Could be a pointer to member, though, if there is an explicit
3563 // scope qualifier for the class.
3564 if (isa<QualifiedDeclRefExpr>(op)) {
3565 DeclContext *Ctx = dcl->getDeclContext();
3566 if (Ctx && Ctx->isRecord())
3567 return Context.getMemberPointerType(op->getType(),
3568 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3569 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003570 } else if (isa<FunctionDecl>(dcl)) {
3571 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003572 // As above.
3573 if (isa<QualifiedDeclRefExpr>(op)) {
3574 DeclContext *Ctx = dcl->getDeclContext();
3575 if (Ctx && Ctx->isRecord())
3576 return Context.getMemberPointerType(op->getType(),
3577 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3578 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003579 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003580 else
Chris Lattner4b009652007-07-25 00:24:17 +00003581 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003582 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003583
Chris Lattner4b009652007-07-25 00:24:17 +00003584 // If the operand has type "type", the result has type "pointer to type".
3585 return Context.getPointerType(op->getType());
3586}
3587
Chris Lattnerda5c0872008-11-23 09:13:29 +00003588QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3589 UsualUnaryConversions(Op);
3590 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003591
Chris Lattnerda5c0872008-11-23 09:13:29 +00003592 // Note that per both C89 and C99, this is always legal, even if ptype is an
3593 // incomplete type or void. It would be possible to warn about dereferencing
3594 // a void pointer, but it's completely well-defined, and such a warning is
3595 // unlikely to catch any mistakes.
3596 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003597 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003598
Chris Lattner77d52da2008-11-20 06:06:08 +00003599 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003600 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003601 return QualType();
3602}
3603
3604static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3605 tok::TokenKind Kind) {
3606 BinaryOperator::Opcode Opc;
3607 switch (Kind) {
3608 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003609 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3610 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003611 case tok::star: Opc = BinaryOperator::Mul; break;
3612 case tok::slash: Opc = BinaryOperator::Div; break;
3613 case tok::percent: Opc = BinaryOperator::Rem; break;
3614 case tok::plus: Opc = BinaryOperator::Add; break;
3615 case tok::minus: Opc = BinaryOperator::Sub; break;
3616 case tok::lessless: Opc = BinaryOperator::Shl; break;
3617 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3618 case tok::lessequal: Opc = BinaryOperator::LE; break;
3619 case tok::less: Opc = BinaryOperator::LT; break;
3620 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3621 case tok::greater: Opc = BinaryOperator::GT; break;
3622 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3623 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3624 case tok::amp: Opc = BinaryOperator::And; break;
3625 case tok::caret: Opc = BinaryOperator::Xor; break;
3626 case tok::pipe: Opc = BinaryOperator::Or; break;
3627 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3628 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3629 case tok::equal: Opc = BinaryOperator::Assign; break;
3630 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3631 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3632 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3633 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3634 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3635 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3636 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3637 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3638 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3639 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3640 case tok::comma: Opc = BinaryOperator::Comma; break;
3641 }
3642 return Opc;
3643}
3644
3645static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3646 tok::TokenKind Kind) {
3647 UnaryOperator::Opcode Opc;
3648 switch (Kind) {
3649 default: assert(0 && "Unknown unary op!");
3650 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3651 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3652 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3653 case tok::star: Opc = UnaryOperator::Deref; break;
3654 case tok::plus: Opc = UnaryOperator::Plus; break;
3655 case tok::minus: Opc = UnaryOperator::Minus; break;
3656 case tok::tilde: Opc = UnaryOperator::Not; break;
3657 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003658 case tok::kw___real: Opc = UnaryOperator::Real; break;
3659 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3660 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3661 }
3662 return Opc;
3663}
3664
Douglas Gregord7f915e2008-11-06 23:29:22 +00003665/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3666/// operator @p Opc at location @c TokLoc. This routine only supports
3667/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003668Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3669 unsigned Op,
3670 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003671 QualType ResultTy; // Result type of the binary operator.
3672 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3673 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3674
3675 switch (Opc) {
3676 default:
3677 assert(0 && "Unknown binary expr!");
3678 case BinaryOperator::Assign:
3679 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3680 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003681 case BinaryOperator::PtrMemD:
3682 case BinaryOperator::PtrMemI:
3683 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3684 Opc == BinaryOperator::PtrMemI);
3685 break;
3686 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003687 case BinaryOperator::Div:
3688 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3689 break;
3690 case BinaryOperator::Rem:
3691 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3692 break;
3693 case BinaryOperator::Add:
3694 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3695 break;
3696 case BinaryOperator::Sub:
3697 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3698 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003699 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003700 case BinaryOperator::Shr:
3701 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3702 break;
3703 case BinaryOperator::LE:
3704 case BinaryOperator::LT:
3705 case BinaryOperator::GE:
3706 case BinaryOperator::GT:
3707 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3708 break;
3709 case BinaryOperator::EQ:
3710 case BinaryOperator::NE:
3711 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3712 break;
3713 case BinaryOperator::And:
3714 case BinaryOperator::Xor:
3715 case BinaryOperator::Or:
3716 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3717 break;
3718 case BinaryOperator::LAnd:
3719 case BinaryOperator::LOr:
3720 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3721 break;
3722 case BinaryOperator::MulAssign:
3723 case BinaryOperator::DivAssign:
3724 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3725 if (!CompTy.isNull())
3726 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3727 break;
3728 case BinaryOperator::RemAssign:
3729 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3730 if (!CompTy.isNull())
3731 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3732 break;
3733 case BinaryOperator::AddAssign:
3734 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3735 if (!CompTy.isNull())
3736 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3737 break;
3738 case BinaryOperator::SubAssign:
3739 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3740 if (!CompTy.isNull())
3741 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3742 break;
3743 case BinaryOperator::ShlAssign:
3744 case BinaryOperator::ShrAssign:
3745 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3746 if (!CompTy.isNull())
3747 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3748 break;
3749 case BinaryOperator::AndAssign:
3750 case BinaryOperator::XorAssign:
3751 case BinaryOperator::OrAssign:
3752 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3753 if (!CompTy.isNull())
3754 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3755 break;
3756 case BinaryOperator::Comma:
3757 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3758 break;
3759 }
3760 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003761 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003762 if (CompTy.isNull())
3763 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3764 else
3765 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003766 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003767}
3768
Chris Lattner4b009652007-07-25 00:24:17 +00003769// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003770Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3771 tok::TokenKind Kind,
3772 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003773 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003774 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003775
Steve Naroff87d58b42007-09-16 03:34:24 +00003776 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3777 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003778
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003779 // If either expression is type-dependent, just build the AST.
3780 // FIXME: We'll need to perform some caching of the result of name
3781 // lookup for operator+.
3782 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003783 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3784 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003785 Context.DependentTy,
3786 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003787 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003788 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3789 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003790 }
3791
Sebastian Redl95216a62009-02-07 00:15:38 +00003792 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003793 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3794 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003795 // If this is one of the assignment operators, we only perform
3796 // overload resolution if the left-hand side is a class or
3797 // enumeration type (C++ [expr.ass]p3).
3798 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3799 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3800 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3801 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003802
Douglas Gregord7f915e2008-11-06 23:29:22 +00003803 // Determine which overloaded operator we're dealing with.
3804 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003805 // Overloading .* is not possible.
3806 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003807 OO_Star, OO_Slash, OO_Percent,
3808 OO_Plus, OO_Minus,
3809 OO_LessLess, OO_GreaterGreater,
3810 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3811 OO_EqualEqual, OO_ExclaimEqual,
3812 OO_Amp,
3813 OO_Caret,
3814 OO_Pipe,
3815 OO_AmpAmp,
3816 OO_PipePipe,
3817 OO_Equal, OO_StarEqual,
3818 OO_SlashEqual, OO_PercentEqual,
3819 OO_PlusEqual, OO_MinusEqual,
3820 OO_LessLessEqual, OO_GreaterGreaterEqual,
3821 OO_AmpEqual, OO_CaretEqual,
3822 OO_PipeEqual,
3823 OO_Comma
3824 };
3825 OverloadedOperatorKind OverOp = OverOps[Opc];
3826
Douglas Gregor5ed15042008-11-18 23:14:02 +00003827 // Add the appropriate overloaded operators (C++ [over.match.oper])
3828 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003829 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003830 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003831 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3832 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003833
3834 // Perform overload resolution.
3835 OverloadCandidateSet::iterator Best;
3836 switch (BestViableFunction(CandidateSet, Best)) {
3837 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003838 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003839 FunctionDecl *FnDecl = Best->Function;
3840
Douglas Gregor70d26122008-11-12 17:17:38 +00003841 if (FnDecl) {
3842 // We matched an overloaded operator. Build a call to that
3843 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003844
Douglas Gregor70d26122008-11-12 17:17:38 +00003845 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3847 if (PerformObjectArgumentInitialization(lhs, Method) ||
3848 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3849 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003850 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003851 } else {
3852 // Convert the arguments.
3853 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3854 "passing") ||
3855 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3856 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003857 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003858 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003859
Douglas Gregor70d26122008-11-12 17:17:38 +00003860 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003861 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003862 = FnDecl->getType()->getAsFunctionType()->getResultType();
3863 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003864
Douglas Gregor70d26122008-11-12 17:17:38 +00003865 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003866 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3867 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003868 UsualUnaryConversions(FnExpr);
3869
Ted Kremenek362abcd2009-02-09 20:51:47 +00003870 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003871 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003872 } else {
3873 // We matched a built-in operator. Convert the arguments, then
3874 // break out so that we will build the appropriate built-in
3875 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003876 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3877 Best->Conversions[0], "passing") ||
3878 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3879 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003880 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003881
3882 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003883 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003884 }
3885
3886 case OR_No_Viable_Function:
3887 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003888 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003889 break;
3890
3891 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003892 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3893 << BinaryOperator::getOpcodeStr(Opc)
3894 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003895 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003896 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003897 }
3898
Douglas Gregor70d26122008-11-12 17:17:38 +00003899 // Either we found no viable overloaded operator or we matched a
3900 // built-in operator. In either case, fall through to trying to
3901 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003902 }
3903
Douglas Gregord7f915e2008-11-06 23:29:22 +00003904 // Build a built-in binary operation.
3905 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003906}
3907
3908// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003909Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3910 tok::TokenKind Op, ExprArg input) {
3911 // FIXME: Input is modified later, but smart pointer not reassigned.
3912 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003913 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003914
3915 if (getLangOptions().CPlusPlus &&
3916 (Input->getType()->isRecordType()
3917 || Input->getType()->isEnumeralType())) {
3918 // Determine which overloaded operator we're dealing with.
3919 static const OverloadedOperatorKind OverOps[] = {
3920 OO_None, OO_None,
3921 OO_PlusPlus, OO_MinusMinus,
3922 OO_Amp, OO_Star,
3923 OO_Plus, OO_Minus,
3924 OO_Tilde, OO_Exclaim,
3925 OO_None, OO_None,
3926 OO_None,
3927 OO_None
3928 };
3929 OverloadedOperatorKind OverOp = OverOps[Opc];
3930
3931 // Add the appropriate overloaded operators (C++ [over.match.oper])
3932 // to the candidate set.
3933 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003934 if (OverOp != OO_None &&
3935 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3936 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003937
3938 // Perform overload resolution.
3939 OverloadCandidateSet::iterator Best;
3940 switch (BestViableFunction(CandidateSet, Best)) {
3941 case OR_Success: {
3942 // We found a built-in operator or an overloaded operator.
3943 FunctionDecl *FnDecl = Best->Function;
3944
3945 if (FnDecl) {
3946 // We matched an overloaded operator. Build a call to that
3947 // operator.
3948
3949 // Convert the arguments.
3950 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3951 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003952 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003953 } else {
3954 // Convert the arguments.
3955 if (PerformCopyInitialization(Input,
3956 FnDecl->getParamDecl(0)->getType(),
3957 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003958 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003959 }
3960
3961 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003962 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003963 = FnDecl->getType()->getAsFunctionType()->getResultType();
3964 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003965
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003966 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003967 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3968 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003969 UsualUnaryConversions(FnExpr);
3970
Sebastian Redl8b769972009-01-19 00:08:26 +00003971 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003972 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003973 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003974 } else {
3975 // We matched a built-in operator. Convert the arguments, then
3976 // break out so that we will build the appropriate built-in
3977 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003978 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3979 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003980 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003981
3982 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003983 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003984 }
3985
3986 case OR_No_Viable_Function:
3987 // No viable function; fall through to handling this as a
3988 // built-in operator, which will produce an error message for us.
3989 break;
3990
3991 case OR_Ambiguous:
3992 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3993 << UnaryOperator::getOpcodeStr(Opc)
3994 << Input->getSourceRange();
3995 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003996 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003997 }
3998
3999 // Either we found no viable overloaded operator or we matched a
4000 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004001 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004002 }
4003
Chris Lattner4b009652007-07-25 00:24:17 +00004004 QualType resultType;
4005 switch (Opc) {
4006 default:
4007 assert(0 && "Unimplemented unary expr!");
4008 case UnaryOperator::PreInc:
4009 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004010 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4011 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004012 break;
4013 case UnaryOperator::AddrOf:
4014 resultType = CheckAddressOfOperand(Input, OpLoc);
4015 break;
4016 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004017 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004018 resultType = CheckIndirectionOperand(Input, OpLoc);
4019 break;
4020 case UnaryOperator::Plus:
4021 case UnaryOperator::Minus:
4022 UsualUnaryConversions(Input);
4023 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004024 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4025 break;
4026 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4027 resultType->isEnumeralType())
4028 break;
4029 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4030 Opc == UnaryOperator::Plus &&
4031 resultType->isPointerType())
4032 break;
4033
Sebastian Redl8b769972009-01-19 00:08:26 +00004034 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4035 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004036 case UnaryOperator::Not: // bitwise complement
4037 UsualUnaryConversions(Input);
4038 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004039 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4040 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4041 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004042 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004043 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004044 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004045 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4046 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004047 break;
4048 case UnaryOperator::LNot: // logical negation
4049 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4050 DefaultFunctionArrayConversion(Input);
4051 resultType = Input->getType();
4052 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004053 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4054 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004055 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004056 // In C++, it's bool. C++ 5.3.1p8
4057 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004058 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004059 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004060 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00004061 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00004062 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004063 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004064 resultType = Input->getType();
4065 break;
4066 }
4067 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004068 return ExprError();
4069 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004070 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004071}
4072
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004073/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4074Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004075 SourceLocation LabLoc,
4076 IdentifierInfo *LabelII) {
4077 // Look up the record for this label identifier.
4078 LabelStmt *&LabelDecl = LabelMap[LabelII];
4079
Daniel Dunbar879788d2008-08-04 16:51:22 +00004080 // If we haven't seen this label yet, create a forward reference. It
4081 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004082 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004083 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004084
4085 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004086 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4087 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004088}
4089
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004090Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004091 SourceLocation RPLoc) { // "({..})"
4092 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4093 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4094 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4095
Eli Friedmanbc941e12009-01-24 23:09:00 +00004096 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4097 if (isFileScope) {
4098 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4099 }
4100
Chris Lattner4b009652007-07-25 00:24:17 +00004101 // FIXME: there are a variety of strange constraints to enforce here, for
4102 // example, it is not possible to goto into a stmt expression apparently.
4103 // More semantic analysis is needed.
4104
4105 // FIXME: the last statement in the compount stmt has its value used. We
4106 // should not warn about it being unused.
4107
4108 // If there are sub stmts in the compound stmt, take the type of the last one
4109 // as the type of the stmtexpr.
4110 QualType Ty = Context.VoidTy;
4111
Chris Lattner200964f2008-07-26 19:51:01 +00004112 if (!Compound->body_empty()) {
4113 Stmt *LastStmt = Compound->body_back();
4114 // If LastStmt is a label, skip down through into the body.
4115 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4116 LastStmt = Label->getSubStmt();
4117
4118 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004119 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004120 }
Chris Lattner4b009652007-07-25 00:24:17 +00004121
Steve Naroff774e4152009-01-21 00:14:39 +00004122 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004123}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004124
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004125Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4126 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004127 SourceLocation TypeLoc,
4128 TypeTy *argty,
4129 OffsetOfComponent *CompPtr,
4130 unsigned NumComponents,
4131 SourceLocation RPLoc) {
4132 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4133 assert(!ArgTy.isNull() && "Missing type argument!");
4134
4135 // We must have at least one component that refers to the type, and the first
4136 // one is known to be a field designator. Verify that the ArgTy represents
4137 // a struct/union/class.
4138 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004139 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004140
4141 // Otherwise, create a compound literal expression as the base, and
4142 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004143 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004144 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004145 IList->setType(ArgTy);
4146 Expr *Res =
4147 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4148
Chris Lattnerb37522e2007-08-31 21:49:13 +00004149 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4150 // GCC extension, diagnose them.
4151 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004152 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4153 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004154
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004155 for (unsigned i = 0; i != NumComponents; ++i) {
4156 const OffsetOfComponent &OC = CompPtr[i];
4157 if (OC.isBrackets) {
4158 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004159 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004160 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004161 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004162 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004163 }
4164
Chris Lattner2af6a802007-08-30 17:59:59 +00004165 // FIXME: C++: Verify that operator[] isn't overloaded.
4166
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004167 // C99 6.5.2.1p1
4168 Expr *Idx = static_cast<Expr*>(OC.U.E);
4169 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004170 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4171 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004172
Steve Naroff774e4152009-01-21 00:14:39 +00004173 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4174 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004175 continue;
4176 }
4177
4178 const RecordType *RC = Res->getType()->getAsRecordType();
4179 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004180 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004181 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004182 }
4183
4184 // Get the decl corresponding to this.
4185 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004186 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004187 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4188 LookupMemberName)
4189 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004190 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004191 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4192 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004193
4194 // FIXME: C++: Verify that MemberDecl isn't a static field.
4195 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004196 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4197 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004198 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4199 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004200 }
4201
Steve Naroff774e4152009-01-21 00:14:39 +00004202 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4203 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004204}
4205
4206
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004207Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004208 TypeTy *arg1, TypeTy *arg2,
4209 SourceLocation RPLoc) {
4210 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4211 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4212
4213 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4214
Steve Naroff774e4152009-01-21 00:14:39 +00004215 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4216 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004217}
4218
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004219Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004220 ExprTy *expr1, ExprTy *expr2,
4221 SourceLocation RPLoc) {
4222 Expr *CondExpr = static_cast<Expr*>(cond);
4223 Expr *LHSExpr = static_cast<Expr*>(expr1);
4224 Expr *RHSExpr = static_cast<Expr*>(expr2);
4225
4226 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4227
4228 // The conditional expression is required to be a constant expression.
4229 llvm::APSInt condEval(32);
4230 SourceLocation ExpLoc;
4231 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004232 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4233 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004234
4235 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4236 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4237 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004238 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4239 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004240}
4241
Steve Naroff52a81c02008-09-03 18:15:37 +00004242//===----------------------------------------------------------------------===//
4243// Clang Extensions.
4244//===----------------------------------------------------------------------===//
4245
4246/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004247void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004248 // Analyze block parameters.
4249 BlockSemaInfo *BSI = new BlockSemaInfo();
4250
4251 // Add BSI to CurBlock.
4252 BSI->PrevBlockInfo = CurBlock;
4253 CurBlock = BSI;
4254
4255 BSI->ReturnType = 0;
4256 BSI->TheScope = BlockScope;
4257
Steve Naroff52059382008-10-10 01:28:17 +00004258 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004259 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004260}
4261
Mike Stumpc1fddff2009-02-04 22:31:32 +00004262void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4263 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4264
4265 if (ParamInfo.getNumTypeObjects() == 0
4266 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4267 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4268
4269 // The type is entirely optional as well, if none, use DependentTy.
4270 if (T.isNull())
4271 T = Context.DependentTy;
4272
4273 // The parameter list is optional, if there was none, assume ().
4274 if (!T->isFunctionType())
4275 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4276
4277 CurBlock->hasPrototype = true;
4278 CurBlock->isVariadic = false;
4279 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4280 .getTypePtr();
4281
4282 if (!RetTy->isDependentType())
4283 CurBlock->ReturnType = RetTy;
4284 return;
4285 }
4286
Steve Naroff52a81c02008-09-03 18:15:37 +00004287 // Analyze arguments to block.
4288 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4289 "Not a function declarator!");
4290 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004291
Steve Naroff52059382008-10-10 01:28:17 +00004292 CurBlock->hasPrototype = FTI.hasPrototype;
4293 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004294
4295 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4296 // no arguments, not a function that takes a single void argument.
4297 if (FTI.hasPrototype &&
4298 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4299 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4300 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4301 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004302 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004303 } else if (FTI.hasPrototype) {
4304 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004305 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4306 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004307 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4308
4309 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4310 .getTypePtr();
4311
4312 if (!RetTy->isDependentType())
4313 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004314 }
Steve Naroff52059382008-10-10 01:28:17 +00004315 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4316
4317 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4318 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4319 // If this has an identifier, add it to the scope stack.
4320 if ((*AI)->getIdentifier())
4321 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004322}
4323
4324/// ActOnBlockError - If there is an error parsing a block, this callback
4325/// is invoked to pop the information about the block from the action impl.
4326void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4327 // Ensure that CurBlock is deleted.
4328 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4329
4330 // Pop off CurBlock, handle nested blocks.
4331 CurBlock = CurBlock->PrevBlockInfo;
4332
4333 // FIXME: Delete the ParmVarDecl objects as well???
4334
4335}
4336
4337/// ActOnBlockStmtExpr - This is called when the body of a block statement
4338/// literal was successfully completed. ^(int x){...}
4339Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4340 Scope *CurScope) {
4341 // Ensure that CurBlock is deleted.
4342 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004343 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004344
Steve Naroff52059382008-10-10 01:28:17 +00004345 PopDeclContext();
4346
Steve Naroff52a81c02008-09-03 18:15:37 +00004347 // Pop off CurBlock, handle nested blocks.
4348 CurBlock = CurBlock->PrevBlockInfo;
4349
4350 QualType RetTy = Context.VoidTy;
4351 if (BSI->ReturnType)
4352 RetTy = QualType(BSI->ReturnType, 0);
4353
4354 llvm::SmallVector<QualType, 8> ArgTypes;
4355 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4356 ArgTypes.push_back(BSI->Params[i]->getType());
4357
4358 QualType BlockTy;
4359 if (!BSI->hasPrototype)
4360 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4361 else
4362 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004363 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004364
4365 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004366
Steve Naroff95029d92008-10-08 18:44:00 +00004367 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004368 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004369}
4370
Nate Begemanbd881ef2008-01-30 20:50:20 +00004371/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004372/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004373/// The number of arguments has already been validated to match the number of
4374/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004375static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4376 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004377 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004378 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004379 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4380 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004381
4382 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004383 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004384 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004385 return true;
4386}
4387
4388Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4389 SourceLocation *CommaLocs,
4390 SourceLocation BuiltinLoc,
4391 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004392 // __builtin_overload requires at least 2 arguments
4393 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004394 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4395 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004396
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004397 // The first argument is required to be a constant expression. It tells us
4398 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004399 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004400 Expr *NParamsExpr = Args[0];
4401 llvm::APSInt constEval(32);
4402 SourceLocation ExpLoc;
4403 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004404 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4405 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004406
4407 // Verify that the number of parameters is > 0
4408 unsigned NumParams = constEval.getZExtValue();
4409 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004410 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4411 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004412 // Verify that we have at least 1 + NumParams arguments to the builtin.
4413 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004414 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4415 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004416
4417 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004418 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004419 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004420 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4421 // UsualUnaryConversions will convert the function DeclRefExpr into a
4422 // pointer to function.
4423 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004424 const FunctionTypeProto *FnType = 0;
4425 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4426 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004427
4428 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4429 // parameters, and the number of parameters must match the value passed to
4430 // the builtin.
4431 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004432 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4433 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004434
4435 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004436 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004437 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004438 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004439 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004440 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4441 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004442 // Remember our match, and continue processing the remaining arguments
4443 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004444 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004445 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004446 BuiltinLoc, RParenLoc);
4447 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004448 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004449 // Return the newly created OverloadExpr node, if we succeded in matching
4450 // exactly one of the candidate functions.
4451 if (OE)
4452 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004453
4454 // If we didn't find a matching function Expr in the __builtin_overload list
4455 // the return an error.
4456 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004457 for (unsigned i = 0; i != NumParams; ++i) {
4458 if (i != 0) typeNames += ", ";
4459 typeNames += Args[i+1]->getType().getAsString();
4460 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004461
Chris Lattner77d52da2008-11-20 06:06:08 +00004462 return Diag(BuiltinLoc, diag::err_overload_no_match)
4463 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004464}
4465
Anders Carlsson36760332007-10-15 20:28:48 +00004466Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4467 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004468 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004469 Expr *E = static_cast<Expr*>(expr);
4470 QualType T = QualType::getFromOpaquePtr(type);
4471
4472 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004473
4474 // Get the va_list type
4475 QualType VaListType = Context.getBuiltinVaListType();
4476 // Deal with implicit array decay; for example, on x86-64,
4477 // va_list is an array, but it's supposed to decay to
4478 // a pointer for va_arg.
4479 if (VaListType->isArrayType())
4480 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004481 // Make sure the input expression also decays appropriately.
4482 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004483
4484 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004485 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004486 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004487 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004488
4489 // FIXME: Warn if a non-POD type is passed in.
4490
Steve Naroff774e4152009-01-21 00:14:39 +00004491 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004492}
4493
Douglas Gregorad4b3792008-11-29 04:51:27 +00004494Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4495 // The type of __null will be int or long, depending on the size of
4496 // pointers on the target.
4497 QualType Ty;
4498 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4499 Ty = Context.IntTy;
4500 else
4501 Ty = Context.LongTy;
4502
Steve Naroff774e4152009-01-21 00:14:39 +00004503 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004504}
4505
Chris Lattner005ed752008-01-04 18:04:52 +00004506bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4507 SourceLocation Loc,
4508 QualType DstType, QualType SrcType,
4509 Expr *SrcExpr, const char *Flavor) {
4510 // Decode the result (notice that AST's are still created for extensions).
4511 bool isInvalid = false;
4512 unsigned DiagKind;
4513 switch (ConvTy) {
4514 default: assert(0 && "Unknown conversion type");
4515 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004516 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004517 DiagKind = diag::ext_typecheck_convert_pointer_int;
4518 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004519 case IntToPointer:
4520 DiagKind = diag::ext_typecheck_convert_int_pointer;
4521 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004522 case IncompatiblePointer:
4523 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4524 break;
4525 case FunctionVoidPointer:
4526 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4527 break;
4528 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004529 // If the qualifiers lost were because we were applying the
4530 // (deprecated) C++ conversion from a string literal to a char*
4531 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4532 // Ideally, this check would be performed in
4533 // CheckPointerTypesForAssignment. However, that would require a
4534 // bit of refactoring (so that the second argument is an
4535 // expression, rather than a type), which should be done as part
4536 // of a larger effort to fix CheckPointerTypesForAssignment for
4537 // C++ semantics.
4538 if (getLangOptions().CPlusPlus &&
4539 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4540 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004541 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4542 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004543 case IntToBlockPointer:
4544 DiagKind = diag::err_int_to_block_pointer;
4545 break;
4546 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004547 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004548 break;
Steve Naroff19608432008-10-14 22:18:38 +00004549 case IncompatibleObjCQualifiedId:
4550 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4551 // it can give a more specific diagnostic.
4552 DiagKind = diag::warn_incompatible_qualified_id;
4553 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004554 case IncompatibleVectors:
4555 DiagKind = diag::warn_incompatible_vectors;
4556 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004557 case Incompatible:
4558 DiagKind = diag::err_typecheck_convert_incompatible;
4559 isInvalid = true;
4560 break;
4561 }
4562
Chris Lattner271d4c22008-11-24 05:29:24 +00004563 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4564 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004565 return isInvalid;
4566}
Anders Carlssond5201b92008-11-30 19:50:32 +00004567
4568bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4569{
4570 Expr::EvalResult EvalResult;
4571
4572 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4573 EvalResult.HasSideEffects) {
4574 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4575
4576 if (EvalResult.Diag) {
4577 // We only show the note if it's not the usual "invalid subexpression"
4578 // or if it's actually in a subexpression.
4579 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4580 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4581 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4582 }
4583
4584 return true;
4585 }
4586
4587 if (EvalResult.Diag) {
4588 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4589 E->getSourceRange();
4590
4591 // Print the reason it's not a constant.
4592 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4593 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4594 }
4595
4596 if (Result)
4597 *Result = EvalResult.Val.getInt();
4598 return false;
4599}