blob: 3b80cd0132b60fefb23c70ce6e05103373c33f83 [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 Lattner57e5f7e2009-02-17 08:12:06 +00001183QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
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 Lattner57e5f7e2009-02-17 08:12:06 +00001195 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1196 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001197 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001198}
1199
1200
Chris Lattner4b009652007-07-25 00:24:17 +00001201
Sebastian Redl8b769972009-01-19 00:08:26 +00001202Action::OwningExprResult
1203Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1204 tok::TokenKind Kind, ExprArg Input) {
1205 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001206
Chris Lattner4b009652007-07-25 00:24:17 +00001207 UnaryOperator::Opcode Opc;
1208 switch (Kind) {
1209 default: assert(0 && "Unknown unary op!");
1210 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1211 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1212 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001213
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001214 if (getLangOptions().CPlusPlus &&
1215 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1216 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001217 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001218 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1219
1220 // C++ [over.inc]p1:
1221 //
1222 // [...] If the function is a member function with one
1223 // parameter (which shall be of type int) or a non-member
1224 // function with two parameters (the second of which shall be
1225 // of type int), it defines the postfix increment operator ++
1226 // for objects of that type. When the postfix increment is
1227 // called as a result of using the ++ operator, the int
1228 // argument will have value zero.
1229 Expr *Args[2] = {
1230 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001231 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1232 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001233 };
1234
1235 // Build the candidate set for overloading
1236 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001237 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1238 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001239
1240 // Perform overload resolution.
1241 OverloadCandidateSet::iterator Best;
1242 switch (BestViableFunction(CandidateSet, Best)) {
1243 case OR_Success: {
1244 // We found a built-in operator or an overloaded operator.
1245 FunctionDecl *FnDecl = Best->Function;
1246
1247 if (FnDecl) {
1248 // We matched an overloaded operator. Build a call to that
1249 // operator.
1250
1251 // Convert the arguments.
1252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1253 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001254 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001255 } else {
1256 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001257 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001258 FnDecl->getParamDecl(0)->getType(),
1259 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001260 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001261 }
1262
1263 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001264 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001265 = FnDecl->getType()->getAsFunctionType()->getResultType();
1266 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001267
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001268 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001269 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001270 SourceLocation());
1271 UsualUnaryConversions(FnExpr);
1272
Sebastian Redl8b769972009-01-19 00:08:26 +00001273 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001274 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1275 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001276 } else {
1277 // We matched a built-in operator. Convert the arguments, then
1278 // break out so that we will build the appropriate built-in
1279 // operator node.
1280 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1281 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001282 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001283
1284 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001285 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001286 }
1287
1288 case OR_No_Viable_Function:
1289 // No viable function; fall through to handling this as a
1290 // built-in operator, which will produce an error message for us.
1291 break;
1292
1293 case OR_Ambiguous:
1294 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1295 << UnaryOperator::getOpcodeStr(Opc)
1296 << Arg->getSourceRange();
1297 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001298 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001299 }
1300
1301 // Either we found no viable overloaded operator or we matched a
1302 // built-in operator. In either case, fall through to trying to
1303 // build a built-in operation.
1304 }
1305
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001306 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1307 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001308 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001309 return ExprError();
1310 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001311 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001312}
1313
Sebastian Redl8b769972009-01-19 00:08:26 +00001314Action::OwningExprResult
1315Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1316 ExprArg Idx, SourceLocation RLoc) {
1317 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1318 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001319
Douglas Gregor80723c52008-11-19 17:17:41 +00001320 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001321 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001322 LHSExp->getType()->isEnumeralType() ||
1323 RHSExp->getType()->isRecordType() ||
1324 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001325 // Add the appropriate overloaded operators (C++ [over.match.oper])
1326 // to the candidate set.
1327 OverloadCandidateSet CandidateSet;
1328 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001329 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1330 SourceRange(LLoc, RLoc)))
1331 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001332
Douglas Gregor80723c52008-11-19 17:17:41 +00001333 // Perform overload resolution.
1334 OverloadCandidateSet::iterator Best;
1335 switch (BestViableFunction(CandidateSet, Best)) {
1336 case OR_Success: {
1337 // We found a built-in operator or an overloaded operator.
1338 FunctionDecl *FnDecl = Best->Function;
1339
1340 if (FnDecl) {
1341 // We matched an overloaded operator. Build a call to that
1342 // operator.
1343
1344 // Convert the arguments.
1345 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1346 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1347 PerformCopyInitialization(RHSExp,
1348 FnDecl->getParamDecl(0)->getType(),
1349 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001350 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001351 } else {
1352 // Convert the arguments.
1353 if (PerformCopyInitialization(LHSExp,
1354 FnDecl->getParamDecl(0)->getType(),
1355 "passing") ||
1356 PerformCopyInitialization(RHSExp,
1357 FnDecl->getParamDecl(1)->getType(),
1358 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001359 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001360 }
1361
1362 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001363 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001364 = FnDecl->getType()->getAsFunctionType()->getResultType();
1365 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001366
Douglas Gregor80723c52008-11-19 17:17:41 +00001367 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001368 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001369 SourceLocation());
1370 UsualUnaryConversions(FnExpr);
1371
Sebastian Redl8b769972009-01-19 00:08:26 +00001372 Base.release();
1373 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001374 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001375 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001376 } else {
1377 // We matched a built-in operator. Convert the arguments, then
1378 // break out so that we will build the appropriate built-in
1379 // operator node.
1380 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1381 "passing") ||
1382 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1383 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001384 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001385
1386 break;
1387 }
1388 }
1389
1390 case OR_No_Viable_Function:
1391 // No viable function; fall through to handling this as a
1392 // built-in operator, which will produce an error message for us.
1393 break;
1394
1395 case OR_Ambiguous:
1396 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1397 << "[]"
1398 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1399 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001400 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001401 }
1402
1403 // Either we found no viable overloaded operator or we matched a
1404 // built-in operator. In either case, fall through to trying to
1405 // build a built-in operation.
1406 }
1407
Chris Lattner4b009652007-07-25 00:24:17 +00001408 // Perform default conversions.
1409 DefaultFunctionArrayConversion(LHSExp);
1410 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001411
Chris Lattner4b009652007-07-25 00:24:17 +00001412 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1413
1414 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001415 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001416 // in the subscript position. As a result, we need to derive the array base
1417 // and index from the expression types.
1418 Expr *BaseExpr, *IndexExpr;
1419 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001420 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001421 BaseExpr = LHSExp;
1422 IndexExpr = RHSExp;
1423 // FIXME: need to deal with const...
1424 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001425 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001426 // Handle the uncommon case of "123[Ptr]".
1427 BaseExpr = RHSExp;
1428 IndexExpr = LHSExp;
1429 // FIXME: need to deal with const...
1430 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001431 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1432 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001433 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001434
Chris Lattner4b009652007-07-25 00:24:17 +00001435 // FIXME: need to deal with const...
1436 ResultType = VTy->getElementType();
1437 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001438 return ExprError(Diag(LHSExp->getLocStart(),
1439 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1440 }
Chris Lattner4b009652007-07-25 00:24:17 +00001441 // C99 6.5.2.1p1
1442 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001443 return ExprError(Diag(IndexExpr->getLocStart(),
1444 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001445
1446 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1447 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001448 // void (*)(int)) and pointers to incomplete types. Functions are not
1449 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001450 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001451 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001452 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001453 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001454
Sebastian Redl8b769972009-01-19 00:08:26 +00001455 Base.release();
1456 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001457 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1458 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001459}
1460
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001461QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001462CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001463 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001464 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001465
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001466 // The vector accessor can't exceed the number of elements.
1467 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001468
1469 // This flag determines whether or not the component is one of the four
1470 // special names that indicate a subset of exactly half the elements are
1471 // to be selected.
1472 bool HalvingSwizzle = false;
1473
1474 // This flag determines whether or not CompName has an 's' char prefix,
1475 // indicating that it is a string of hex values to be used as vector indices.
1476 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001477
1478 // Check that we've found one of the special components, or that the component
1479 // names must come from the same set.
1480 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001481 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1482 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001483 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001484 do
1485 compStr++;
1486 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001487 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001488 do
1489 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001490 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001491 }
Nate Begeman1486b502009-01-18 01:47:54 +00001492
1493 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001494 // We didn't get to the end of the string. This means the component names
1495 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001496 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1497 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001498 return QualType();
1499 }
Nate Begeman1486b502009-01-18 01:47:54 +00001500
1501 // Ensure no component accessor exceeds the width of the vector type it
1502 // operates on.
1503 if (!HalvingSwizzle) {
1504 compStr = CompName.getName();
1505
1506 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001507 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001508
1509 while (*compStr) {
1510 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1511 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1512 << baseType << SourceRange(CompLoc);
1513 return QualType();
1514 }
1515 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001516 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001517
Nate Begeman1486b502009-01-18 01:47:54 +00001518 // If this is a halving swizzle, verify that the base type has an even
1519 // number of elements.
1520 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001521 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001522 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001523 return QualType();
1524 }
1525
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001526 // The component accessor looks fine - now we need to compute the actual type.
1527 // The vector type is implied by the component accessor. For example,
1528 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001529 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001530 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001531 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1532 : CompName.getLength();
1533 if (HexSwizzle)
1534 CompSize--;
1535
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001536 if (CompSize == 1)
1537 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001538
Nate Begemanaf6ed502008-04-18 23:10:10 +00001539 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001540 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001541 // diagostics look bad. We want extended vector types to appear built-in.
1542 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1543 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1544 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001545 }
1546 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001547}
1548
Chris Lattner2cb744b2009-02-15 22:43:40 +00001549
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001550/// constructSetterName - Return the setter name for the given
1551/// identifier, i.e. "set" + Name where the initial character of Name
1552/// has been capitalized.
1553// FIXME: Merge with same routine in Parser. But where should this
1554// live?
1555static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1556 const IdentifierInfo *Name) {
1557 llvm::SmallString<100> SelectorName;
1558 SelectorName = "set";
1559 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1560 SelectorName[3] = toupper(SelectorName[3]);
1561 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1562}
1563
Sebastian Redl8b769972009-01-19 00:08:26 +00001564Action::OwningExprResult
1565Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1566 tok::TokenKind OpKind, SourceLocation MemberLoc,
1567 IdentifierInfo &Member) {
1568 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001569 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001570
1571 // Perform default conversions.
1572 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001573
Steve Naroff2cb66382007-07-26 03:11:44 +00001574 QualType BaseType = BaseExpr->getType();
1575 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001576
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001577 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1578 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001579 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001580 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001581 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001582 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001583 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1584 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001585 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001586 return ExprError(Diag(MemberLoc,
1587 diag::err_typecheck_member_reference_arrow)
1588 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001589 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001590
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001591 // Handle field access to simple records. This also handles access to fields
1592 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001593 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001594 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001595 if (DiagnoseIncompleteType(OpLoc, BaseType,
1596 diag::err_typecheck_incomplete_tag,
1597 BaseExpr->getSourceRange()))
1598 return ExprError();
1599
Steve Naroff2cb66382007-07-26 03:11:44 +00001600 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001601 // FIXME: Qualified name lookup for C++ is a bit more complicated
1602 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001603 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001604 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001605 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001606
Douglas Gregor09be81b2009-02-04 17:27:36 +00001607 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001608 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001609 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1610 << &Member << BaseExpr->getSourceRange());
1611 else if (Result.isAmbiguous()) {
1612 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1613 MemberLoc, BaseExpr->getSourceRange());
1614 return ExprError();
1615 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001616 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001617
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001618 // If the decl being referenced had an error, return an error for this
1619 // sub-expr without emitting another error, in order to avoid cascading
1620 // error cases.
1621 if (MemberDecl->isInvalidDecl())
1622 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001623
1624 // Check if referencing a field with __attribute__((deprecated)).
1625 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001626
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001627 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001628 // We may have found a field within an anonymous union or struct
1629 // (C++ [class.union]).
1630 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001631 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001632 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001633
Douglas Gregor82d44772008-12-20 23:49:58 +00001634 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1635 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001636 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001637 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1638 MemberType = Ref->getPointeeType();
1639 else {
1640 unsigned combinedQualifiers =
1641 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001642 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001643 combinedQualifiers &= ~QualType::Const;
1644 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1645 }
Eli Friedman76b49832008-02-06 22:48:16 +00001646
Steve Naroff774e4152009-01-21 00:14:39 +00001647 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1648 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001649 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001650 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001651 Var, MemberLoc,
1652 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001653 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001654 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1655 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001656 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001657 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001658 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001659 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001660 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001661 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001662 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001663 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001664 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1665 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001666
Douglas Gregor82d44772008-12-20 23:49:58 +00001667 // We found a declaration kind that we didn't expect. This is a
1668 // generic error message that tells the user that she can't refer
1669 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001670 return ExprError(Diag(MemberLoc,
1671 diag::err_typecheck_member_reference_unknown)
1672 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001673 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001674
Chris Lattnere9d71612008-07-21 04:59:05 +00001675 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1676 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001677 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001678 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001679 // If the decl being referenced had an error, return an error for this
1680 // sub-expr without emitting another error, in order to avoid cascading
1681 // error cases.
1682 if (IV->isInvalidDecl())
1683 return ExprError();
1684
Chris Lattner2a3bef92009-02-16 17:19:12 +00001685 // Check if referencing a field with __attribute__((deprecated)).
1686 DiagnoseUseOfDeprecatedDecl(IV, MemberLoc);
1687
Steve Naroff774e4152009-01-21 00:14:39 +00001688 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1689 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001690 OpKind == tok::arrow);
1691 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001692 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001693 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001694 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1695 << IFTy->getDecl()->getDeclName() << &Member
1696 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001697 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001698
Chris Lattnere9d71612008-07-21 04:59:05 +00001699 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1700 // pointer to a (potentially qualified) interface type.
1701 const PointerType *PTy;
1702 const ObjCInterfaceType *IFTy;
1703 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1704 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1705 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001706
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001707 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001708 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1709 // Check if referencing a property with __attribute__((deprecated)).
1710 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1711
Steve Naroff774e4152009-01-21 00:14:39 +00001712 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001713 MemberLoc, BaseExpr));
1714 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001715
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001716 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001717 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1718 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001719 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1720 // Check if referencing a property with __attribute__((deprecated)).
1721 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1722
Steve Naroff774e4152009-01-21 00:14:39 +00001723 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001724 MemberLoc, BaseExpr));
1725 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001726
1727 // If that failed, look for an "implicit" property by seeing if the nullary
1728 // selector is implemented.
1729
1730 // FIXME: The logic for looking up nullary and unary selectors should be
1731 // shared with the code in ActOnInstanceMessage.
1732
1733 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1734 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001735
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001736 // If this reference is in an @implementation, check for 'private' methods.
1737 if (!Getter)
1738 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1739 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1740 if (ObjCImplementationDecl *ImpDecl =
1741 ObjCImplementations[ClassDecl->getIdentifier()])
1742 Getter = ImpDecl->getInstanceMethod(Sel);
1743
Steve Naroff04151f32008-10-22 19:16:27 +00001744 // Look through local category implementations associated with the class.
1745 if (!Getter) {
1746 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1747 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1748 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1749 }
1750 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001751 if (Getter) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001752 // Check if referencing a property with __attribute__((deprecated)).
1753 DiagnoseUseOfDeprecatedDecl(Getter, MemberLoc);
1754
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001755 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001756 // will look for the matching setter, in case it is needed.
1757 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1758 &Member);
1759 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1760 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1761 if (!Setter) {
1762 // If this reference is in an @implementation, also check for 'private'
1763 // methods.
1764 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1765 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1766 if (ObjCImplementationDecl *ImpDecl =
1767 ObjCImplementations[ClassDecl->getIdentifier()])
1768 Setter = ImpDecl->getInstanceMethod(SetterSel);
1769 }
1770 // Look through local category implementations associated with the class.
1771 if (!Setter) {
1772 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1773 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1774 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1775 }
1776 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001777
Chris Lattner51f6fb32009-02-16 18:35:08 +00001778 if (Setter)
1779 // Check if referencing a property with __attribute__((deprecated)).
1780 DiagnoseUseOfDeprecatedDecl(Setter, MemberLoc);
1781
1782
Sebastian Redl8b769972009-01-19 00:08:26 +00001783 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001784 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1785 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001786 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001787
1788 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1789 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001790 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001791 // Handle properties on qualified "id" protocols.
1792 const ObjCQualifiedIdType *QIdTy;
1793 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1794 // Check protocols on qualified interfaces.
1795 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001796 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001797 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1798 // Check if referencing a property with __attribute__((deprecated)).
1799 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1800
Steve Naroff774e4152009-01-21 00:14:39 +00001801 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001802 MemberLoc, BaseExpr));
1803 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001804 // Also must look for a getter name which uses property syntax.
1805 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1806 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001807 // Check if referencing a property with __attribute__((deprecated)).
1808 DiagnoseUseOfDeprecatedDecl(OMD, MemberLoc);
1809
Steve Naroff774e4152009-01-21 00:14:39 +00001810 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1811 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001812 }
1813 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001814
1815 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1816 << &Member << BaseType);
1817 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001818 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001819 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001820 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1821 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001822 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001823 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1824 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001825 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001826
1827 return ExprError(Diag(MemberLoc,
1828 diag::err_typecheck_member_reference_struct_union)
1829 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001830}
1831
Douglas Gregor3257fb52008-12-22 05:46:06 +00001832/// ConvertArgumentsForCall - Converts the arguments specified in
1833/// Args/NumArgs to the parameter types of the function FDecl with
1834/// function prototype Proto. Call is the call expression itself, and
1835/// Fn is the function expression. For a C++ member function, this
1836/// routine does not attempt to convert the object argument. Returns
1837/// true if the call is ill-formed.
1838bool
1839Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1840 FunctionDecl *FDecl,
1841 const FunctionTypeProto *Proto,
1842 Expr **Args, unsigned NumArgs,
1843 SourceLocation RParenLoc) {
1844 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1845 // assignment, to the types of the corresponding parameter, ...
1846 unsigned NumArgsInProto = Proto->getNumArgs();
1847 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001848 bool Invalid = false;
1849
Douglas Gregor3257fb52008-12-22 05:46:06 +00001850 // If too few arguments are available (and we don't have default
1851 // arguments for the remaining parameters), don't make the call.
1852 if (NumArgs < NumArgsInProto) {
1853 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1854 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1855 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1856 // Use default arguments for missing arguments
1857 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001858 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001859 }
1860
1861 // If too many are passed and not variadic, error on the extras and drop
1862 // them.
1863 if (NumArgs > NumArgsInProto) {
1864 if (!Proto->isVariadic()) {
1865 Diag(Args[NumArgsInProto]->getLocStart(),
1866 diag::err_typecheck_call_too_many_args)
1867 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1868 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1869 Args[NumArgs-1]->getLocEnd());
1870 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001871 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001872 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001873 }
1874 NumArgsToCheck = NumArgsInProto;
1875 }
1876
1877 // Continue to check argument types (even if we have too few/many args).
1878 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1879 QualType ProtoArgType = Proto->getArgType(i);
1880
1881 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001882 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001883 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001884
1885 // Pass the argument.
1886 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1887 return true;
1888 } else
1889 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001890 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001891 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001892
Douglas Gregor3257fb52008-12-22 05:46:06 +00001893 Call->setArg(i, Arg);
1894 }
1895
1896 // If this is a variadic call, handle args passed through "...".
1897 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001898 VariadicCallType CallType = VariadicFunction;
1899 if (Fn->getType()->isBlockPointerType())
1900 CallType = VariadicBlock; // Block
1901 else if (isa<MemberExpr>(Fn))
1902 CallType = VariadicMethod;
1903
Douglas Gregor3257fb52008-12-22 05:46:06 +00001904 // Promote the arguments (C99 6.5.2.2p7).
1905 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1906 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001907 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001908 Call->setArg(i, Arg);
1909 }
1910 }
1911
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001912 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001913}
1914
Steve Naroff87d58b42007-09-16 03:34:24 +00001915/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001916/// This provides the location of the left/right parens and a list of comma
1917/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001918Action::OwningExprResult
1919Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1920 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001921 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001922 unsigned NumArgs = args.size();
1923 Expr *Fn = static_cast<Expr *>(fn.release());
1924 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001925 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001926 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001927 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001928
Douglas Gregor3257fb52008-12-22 05:46:06 +00001929 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001930 // Determine whether this is a dependent call inside a C++ template,
1931 // in which case we won't do any semantic analysis now.
1932 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1933 bool Dependent = false;
1934 if (Fn->isTypeDependent())
1935 Dependent = true;
1936 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1937 Dependent = true;
1938
1939 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001940 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001941 Context.DependentTy, RParenLoc));
1942
1943 // Determine whether this is a call to an object (C++ [over.call.object]).
1944 if (Fn->getType()->isRecordType())
1945 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1946 CommaLocs, RParenLoc));
1947
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001948 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001949 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1950 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1951 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001952 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1953 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001954 }
1955
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001956 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001957 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001958 Expr *FnExpr = Fn;
1959 bool ADL = true;
1960 while (true) {
1961 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1962 FnExpr = IcExpr->getSubExpr();
1963 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001964 // Parentheses around a function disable ADL
1965 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001966 ADL = false;
1967 FnExpr = PExpr->getSubExpr();
1968 } else if (isa<UnaryOperator>(FnExpr) &&
1969 cast<UnaryOperator>(FnExpr)->getOpcode()
1970 == UnaryOperator::AddrOf) {
1971 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001972 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1973 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1974 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1975 break;
1976 } else if (UnresolvedFunctionNameExpr *DepName
1977 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1978 UnqualifiedName = DepName->getName();
1979 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001980 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001981 // Any kind of name that does not refer to a declaration (or
1982 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1983 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001984 break;
1985 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001986 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001987
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001988 OverloadedFunctionDecl *Ovl = 0;
1989 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001990 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001991 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1992 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001993
Douglas Gregorfcb19192009-02-11 23:02:49 +00001994 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001995 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001996 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001997 ADL = false;
1998
Douglas Gregorfcb19192009-02-11 23:02:49 +00001999 // We don't perform ADL in C.
2000 if (!getLangOptions().CPlusPlus)
2001 ADL = false;
2002
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002003 if (Ovl || ADL) {
2004 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2005 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002006 NumArgs, CommaLocs, RParenLoc, ADL);
2007 if (!FDecl)
2008 return ExprError();
2009
2010 // Update Fn to refer to the actual function selected.
2011 Expr *NewFn = 0;
2012 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002013 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002014 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2015 QDRExpr->getLocation(),
2016 false, false,
2017 QDRExpr->getSourceRange().getBegin());
2018 else
2019 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2020 Fn->getSourceRange().getBegin());
2021 Fn->Destroy(Context);
2022 Fn = NewFn;
2023 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002024 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002025
2026 // Promote the function operand.
2027 UsualUnaryConversions(Fn);
2028
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002029 // Make the call expr early, before semantic checks. This guarantees cleanup
2030 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00002031 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
2032 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002033 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2034 Args, NumArgs,
2035 Context.BoolTy,
2036 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002037
Steve Naroffd6163f32008-09-05 22:11:13 +00002038 const FunctionType *FuncT;
2039 if (!Fn->getType()->isBlockPointerType()) {
2040 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2041 // have type pointer to function".
2042 const PointerType *PT = Fn->getType()->getAsPointerType();
2043 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002044 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2045 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002046 FuncT = PT->getPointeeType()->getAsFunctionType();
2047 } else { // This is a block call.
2048 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2049 getAsFunctionType();
2050 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002051 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002052 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2053 << Fn->getType() << Fn->getSourceRange());
2054
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002055 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002056 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002057
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002058 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002059 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2060 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002061 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002062 } else {
2063 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002064
Steve Naroffdb65e052007-08-28 23:30:39 +00002065 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002066 for (unsigned i = 0; i != NumArgs; i++) {
2067 Expr *Arg = Args[i];
2068 DefaultArgumentPromotion(Arg);
2069 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002070 }
Chris Lattner4b009652007-07-25 00:24:17 +00002071 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002072
Douglas Gregor3257fb52008-12-22 05:46:06 +00002073 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2074 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002075 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2076 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002077
Chris Lattner2e64c072007-08-10 20:18:51 +00002078 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002079 if (FDecl)
2080 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002081
Sebastian Redl8b769972009-01-19 00:08:26 +00002082 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002083}
2084
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002085Action::OwningExprResult
2086Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2087 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002088 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002089 QualType literalType = QualType::getFromOpaquePtr(Ty);
2090 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002091 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002092 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002093
Eli Friedman8c2173d2008-05-20 05:22:08 +00002094 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002095 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002096 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2097 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002098 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2099 diag::err_typecheck_decl_incomplete_type,
2100 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002101 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002102
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002103 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002104 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002105 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002106
Chris Lattnere5cb5862008-12-04 23:50:19 +00002107 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002108 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002109 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002110 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002111 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002112 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002113 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2114 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002115}
2116
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002117Action::OwningExprResult
2118Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2119 InitListDesignations &Designators,
2120 SourceLocation RBraceLoc) {
2121 unsigned NumInit = initlist.size();
2122 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002123
Steve Naroff0acc9c92007-09-15 18:49:24 +00002124 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002125 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002126
Steve Naroff774e4152009-01-21 00:14:39 +00002127 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002128 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002129 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002130 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002131}
2132
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002133/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002134bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002135 UsualUnaryConversions(castExpr);
2136
2137 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2138 // type needs to be scalar.
2139 if (castType->isVoidType()) {
2140 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002141 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2142 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002143 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002144 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2145 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2146 (castType->isStructureType() || castType->isUnionType())) {
2147 // GCC struct/union extension: allow cast to self.
2148 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2149 << castType << castExpr->getSourceRange();
2150 } else if (castType->isUnionType()) {
2151 // GCC cast to union extension
2152 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2153 RecordDecl::field_iterator Field, FieldEnd;
2154 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2155 Field != FieldEnd; ++Field) {
2156 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2157 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2158 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2159 << castExpr->getSourceRange();
2160 break;
2161 }
2162 }
2163 if (Field == FieldEnd)
2164 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2165 << castExpr->getType() << castExpr->getSourceRange();
2166 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002167 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002168 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002169 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002170 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002171 } else if (!castExpr->getType()->isScalarType() &&
2172 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002173 return Diag(castExpr->getLocStart(),
2174 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002175 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002176 } else if (castExpr->getType()->isVectorType()) {
2177 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2178 return true;
2179 } else if (castType->isVectorType()) {
2180 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2181 return true;
2182 }
2183 return false;
2184}
2185
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002186bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002187 assert(VectorTy->isVectorType() && "Not a vector type!");
2188
2189 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002190 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002191 return Diag(R.getBegin(),
2192 Ty->isVectorType() ?
2193 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002194 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002195 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002196 } else
2197 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002198 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002199 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002200
2201 return false;
2202}
2203
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002204Action::OwningExprResult
2205Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2206 SourceLocation RParenLoc, ExprArg Op) {
2207 assert((Ty != 0) && (Op.get() != 0) &&
2208 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002209
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002210 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002211 QualType castType = QualType::getFromOpaquePtr(Ty);
2212
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002213 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002214 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002215 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002216 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002217}
2218
Chris Lattner98a425c2007-11-26 01:40:58 +00002219/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2220/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002221inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Chris Lattnere2897262009-02-18 04:28:32 +00002222 Expr *&Cond, Expr *&LHS, Expr *&RHS, SourceLocation QuestionLoc) {
2223 UsualUnaryConversions(Cond);
2224 UsualUnaryConversions(LHS);
2225 UsualUnaryConversions(RHS);
2226 QualType CondTy = Cond->getType();
2227 QualType LHSTy = LHS->getType();
2228 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002229
2230 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002231 if (!Cond->isTypeDependent()) {
2232 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2233 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2234 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002235 return QualType();
2236 }
Chris Lattner4b009652007-07-25 00:24:17 +00002237 }
Chris Lattner992ae932008-01-06 22:42:25 +00002238
2239 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002240 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002241 return Context.DependentTy;
2242
Chris Lattner992ae932008-01-06 22:42:25 +00002243 // If both operands have arithmetic type, do the usual arithmetic conversions
2244 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002245 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2246 UsualArithmeticConversions(LHS, RHS);
2247 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002248 }
Chris Lattner992ae932008-01-06 22:42:25 +00002249
2250 // If both operands are the same structure or union type, the result is that
2251 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002252 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2253 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002254 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002255 // "If both the operands have structure or union type, the result has
2256 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002257 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002258 }
Chris Lattner992ae932008-01-06 22:42:25 +00002259
2260 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002261 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002262 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2263 if (!LHSTy->isVoidType())
2264 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2265 << RHS->getSourceRange();
2266 if (!RHSTy->isVoidType())
2267 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2268 << LHS->getSourceRange();
2269 ImpCastExprToType(LHS, Context.VoidTy);
2270 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002271 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002272 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002273 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2274 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002275 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2276 Context.isObjCObjectPointerType(LHSTy)) &&
2277 RHS->isNullPointerConstant(Context)) {
2278 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2279 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002280 }
Chris Lattnere2897262009-02-18 04:28:32 +00002281 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2282 Context.isObjCObjectPointerType(RHSTy)) &&
2283 LHS->isNullPointerConstant(Context)) {
2284 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2285 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002286 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002287 // Handle the case where both operands are pointers before we handle null
2288 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002289 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2290 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002291 // get the "pointed to" types
2292 QualType lhptee = LHSPT->getPointeeType();
2293 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002294
Chris Lattner71225142007-07-31 21:27:01 +00002295 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2296 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002297 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002298 // Figure out necessary qualifiers (C99 6.5.15p6)
2299 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002300 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002301 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2302 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002303 return destType;
2304 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002305 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002306 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002307 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002308 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2309 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002310 return destType;
2311 }
Chris Lattner4b009652007-07-25 00:24:17 +00002312
Chris Lattnere2897262009-02-18 04:28:32 +00002313 QualType compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002314
2315 // If either type is an Objective-C object type then check
2316 // compatibility according to Objective-C.
Chris Lattnere2897262009-02-18 04:28:32 +00002317 if (Context.isObjCObjectPointerType(LHSTy) ||
2318 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002319 // If both operands are interfaces and either operand can be
2320 // assigned to the other, use that type as the composite
2321 // type. This allows
2322 // xxx ? (A*) a : (B*) b
2323 // where B is a subclass of A.
2324 //
2325 // Additionally, as for assignment, if either type is 'id'
2326 // allow silent coercion. Finally, if the types are
2327 // incompatible then make sure to use 'id' as the composite
2328 // type so the result is acceptable for sending messages to.
2329
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002330 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2331 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002332 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2333 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2334 if (LHSIface && RHSIface &&
2335 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002336 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002337 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002338 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002339 compositeType = RHSTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002340 } else if (Context.isObjCIdStructType(lhptee) ||
2341 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002342 compositeType = Context.getObjCIdType();
2343 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002344 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2345 << LHSTy << RHSTy
2346 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002347 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002348 ImpCastExprToType(LHS, incompatTy);
2349 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002350 return incompatTy;
2351 }
2352 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2353 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002354 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2355 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002356 // In this situation, we assume void* type. No especially good
2357 // reason, but this is what gcc does, and we do have to pick
2358 // to get a consistent AST.
2359 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002360 ImpCastExprToType(LHS, incompatTy);
2361 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002362 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002363 }
2364 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002365 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2366 // differently qualified versions of compatible types, the result type is
2367 // a pointer to an appropriately qualified version of the *composite*
2368 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002369 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002370 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002371 ImpCastExprToType(LHS, compositeType);
2372 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002373 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002374 }
Chris Lattner4b009652007-07-25 00:24:17 +00002375 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002376 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2377 // evaluates to "struct objc_object *" (and is handled above when comparing
2378 // id with statically typed objects).
Chris Lattnere2897262009-02-18 04:28:32 +00002379 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002380 // GCC allows qualified id and any Objective-C type to devolve to
2381 // id. Currently localizing to here until clear this should be
2382 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002383 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2384 (LHSTy->isObjCQualifiedIdType() &&
2385 Context.isObjCObjectPointerType(RHSTy)) ||
2386 (RHSTy->isObjCQualifiedIdType() &&
2387 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002388 // FIXME: This is not the correct composite type. This only
2389 // happens to work because id can more or less be used anywhere,
2390 // however this may change the type of method sends.
2391 // FIXME: gcc adds some type-checking of the arguments and emits
2392 // (confusing) incompatible comparison warnings in some
2393 // cases. Investigate.
2394 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002395 ImpCastExprToType(LHS, compositeType);
2396 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002397 return compositeType;
2398 }
2399 }
2400
Steve Naroff3eac7692008-09-10 19:17:48 +00002401 // Selection between block pointer types is ok as long as they are the same.
Chris Lattnere2897262009-02-18 04:28:32 +00002402 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2403 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2404 return LHSTy;
Steve Naroff3eac7692008-09-10 19:17:48 +00002405
Chris Lattner992ae932008-01-06 22:42:25 +00002406 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002407 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2408 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002409 return QualType();
2410}
2411
Steve Naroff87d58b42007-09-16 03:34:24 +00002412/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002413/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002414Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2415 SourceLocation ColonLoc,
2416 ExprArg Cond, ExprArg LHS,
2417 ExprArg RHS) {
2418 Expr *CondExpr = (Expr *) Cond.get();
2419 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002420
2421 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2422 // was the condition.
2423 bool isLHSNull = LHSExpr == 0;
2424 if (isLHSNull)
2425 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002426
2427 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002428 RHSExpr, QuestionLoc);
2429 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002430 return ExprError();
2431
2432 Cond.release();
2433 LHS.release();
2434 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002435 return Owned(new (Context) ConditionalOperator(CondExpr,
2436 isLHSNull ? 0 : LHSExpr,
2437 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002438}
2439
Chris Lattner4b009652007-07-25 00:24:17 +00002440
2441// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2442// being closely modeled after the C99 spec:-). The odd characteristic of this
2443// routine is it effectively iqnores the qualifiers on the top level pointee.
2444// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2445// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002446Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002447Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2448 QualType lhptee, rhptee;
2449
2450 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002451 lhptee = lhsType->getAsPointerType()->getPointeeType();
2452 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002453
2454 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002455 lhptee = Context.getCanonicalType(lhptee);
2456 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002457
Chris Lattner005ed752008-01-04 18:04:52 +00002458 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002459
2460 // C99 6.5.16.1p1: This following citation is common to constraints
2461 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2462 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002463 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002464 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002465 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002466
2467 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2468 // incomplete type and the other is a pointer to a qualified or unqualified
2469 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002470 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002471 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002472 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002473
2474 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002475 assert(rhptee->isFunctionType());
2476 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002477 }
2478
2479 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002480 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002481 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002482
2483 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002484 assert(lhptee->isFunctionType());
2485 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002486 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002487
2488 // Check for ObjC interfaces
2489 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2490 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2491 if (LHSIface && RHSIface &&
2492 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2493 return ConvTy;
2494
2495 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002496 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002497 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002498 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002499 return ConvTy;
2500
Chris Lattner4b009652007-07-25 00:24:17 +00002501 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2502 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002503 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2504 rhptee.getUnqualifiedType()))
2505 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002506 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002507}
2508
Steve Naroff3454b6c2008-09-04 15:10:53 +00002509/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2510/// block pointer types are compatible or whether a block and normal pointer
2511/// are compatible. It is more restrict than comparing two function pointer
2512// types.
2513Sema::AssignConvertType
2514Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2515 QualType rhsType) {
2516 QualType lhptee, rhptee;
2517
2518 // get the "pointed to" type (ignoring qualifiers at the top level)
2519 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2520 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2521
2522 // make sure we operate on the canonical type
2523 lhptee = Context.getCanonicalType(lhptee);
2524 rhptee = Context.getCanonicalType(rhptee);
2525
2526 AssignConvertType ConvTy = Compatible;
2527
2528 // For blocks we enforce that qualifiers are identical.
2529 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2530 ConvTy = CompatiblePointerDiscardsQualifiers;
2531
2532 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2533 return IncompatibleBlockPointer;
2534 return ConvTy;
2535}
2536
Chris Lattner4b009652007-07-25 00:24:17 +00002537/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2538/// has code to accommodate several GCC extensions when type checking
2539/// pointers. Here are some objectionable examples that GCC considers warnings:
2540///
2541/// int a, *pint;
2542/// short *pshort;
2543/// struct foo *pfoo;
2544///
2545/// pint = pshort; // warning: assignment from incompatible pointer type
2546/// a = pint; // warning: assignment makes integer from pointer without a cast
2547/// pint = a; // warning: assignment makes pointer from integer without a cast
2548/// pint = pfoo; // warning: assignment from incompatible pointer type
2549///
2550/// As a result, the code for dealing with pointers is more complex than the
2551/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002552///
Chris Lattner005ed752008-01-04 18:04:52 +00002553Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002554Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002555 // Get canonical types. We're not formatting these types, just comparing
2556 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002557 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2558 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002559
2560 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002561 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002562
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002563 // If the left-hand side is a reference type, then we are in a
2564 // (rare!) case where we've allowed the use of references in C,
2565 // e.g., as a parameter type in a built-in function. In this case,
2566 // just make sure that the type referenced is compatible with the
2567 // right-hand side type. The caller is responsible for adjusting
2568 // lhsType so that the resulting expression does not have reference
2569 // type.
2570 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2571 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002572 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002573 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002574 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002575
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002576 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2577 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002578 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002579 // Relax integer conversions like we do for pointers below.
2580 if (rhsType->isIntegerType())
2581 return IntToPointer;
2582 if (lhsType->isIntegerType())
2583 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002584 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002585 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002586
Nate Begemanc5f0f652008-07-14 18:02:46 +00002587 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002588 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002589 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2590 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002591 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002592
Nate Begemanc5f0f652008-07-14 18:02:46 +00002593 // If we are allowing lax vector conversions, and LHS and RHS are both
2594 // vectors, the total size only needs to be the same. This is a bitcast;
2595 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002596 if (getLangOptions().LaxVectorConversions &&
2597 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002598 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002599 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002600 }
2601 return Incompatible;
2602 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002603
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002604 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002605 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002606
Chris Lattner390564e2008-04-07 06:49:41 +00002607 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002608 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002609 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002610
Chris Lattner390564e2008-04-07 06:49:41 +00002611 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002612 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002613
Steve Naroffa982c712008-09-29 18:10:17 +00002614 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002615 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002616 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002617
2618 // Treat block pointers as objects.
2619 if (getLangOptions().ObjC1 &&
2620 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2621 return Compatible;
2622 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002623 return Incompatible;
2624 }
2625
2626 if (isa<BlockPointerType>(lhsType)) {
2627 if (rhsType->isIntegerType())
2628 return IntToPointer;
2629
Steve Naroffa982c712008-09-29 18:10:17 +00002630 // Treat block pointers as objects.
2631 if (getLangOptions().ObjC1 &&
2632 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2633 return Compatible;
2634
Steve Naroff3454b6c2008-09-04 15:10:53 +00002635 if (rhsType->isBlockPointerType())
2636 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2637
2638 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2639 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002640 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002641 }
Chris Lattner1853da22008-01-04 23:18:45 +00002642 return Incompatible;
2643 }
2644
Chris Lattner390564e2008-04-07 06:49:41 +00002645 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002646 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002647 if (lhsType == Context.BoolTy)
2648 return Compatible;
2649
2650 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002651 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002652
Chris Lattner390564e2008-04-07 06:49:41 +00002653 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002654 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002655
2656 if (isa<BlockPointerType>(lhsType) &&
2657 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002658 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002659 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002660 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002661
Chris Lattner1853da22008-01-04 23:18:45 +00002662 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002663 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002664 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002665 }
2666 return Incompatible;
2667}
2668
Chris Lattner005ed752008-01-04 18:04:52 +00002669Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002670Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002671 if (getLangOptions().CPlusPlus) {
2672 if (!lhsType->isRecordType()) {
2673 // C++ 5.17p3: If the left operand is not of class type, the
2674 // expression is implicitly converted (C++ 4) to the
2675 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002676 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2677 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002678 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002679 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002680 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002681 }
2682
2683 // FIXME: Currently, we fall through and treat C++ classes like C
2684 // structures.
2685 }
2686
Steve Naroffcdee22d2007-11-27 17:58:44 +00002687 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2688 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002689 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2690 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002691 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002692 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002693 return Compatible;
2694 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002695
2696 // We don't allow conversion of non-null-pointer constants to integers.
2697 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2698 return IntToBlockPointer;
2699
Chris Lattner5f505bf2007-10-16 02:55:40 +00002700 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002701 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002702 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002703 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002704 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002705 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002706 if (!lhsType->isReferenceType())
2707 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002708
Chris Lattner005ed752008-01-04 18:04:52 +00002709 Sema::AssignConvertType result =
2710 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002711
2712 // C99 6.5.16.1p2: The value of the right operand is converted to the
2713 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002714 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2715 // so that we can use references in built-in functions even in C.
2716 // The getNonReferenceType() call makes sure that the resulting expression
2717 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002718 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002719 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002720 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002721}
2722
Chris Lattner005ed752008-01-04 18:04:52 +00002723Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002724Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2725 return CheckAssignmentConstraints(lhsType, rhsType);
2726}
2727
Chris Lattner1eafdea2008-11-18 01:30:42 +00002728QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002729 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002730 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002731 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002732 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002733}
2734
Chris Lattner1eafdea2008-11-18 01:30:42 +00002735inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002736 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002737 // For conversion purposes, we ignore any qualifiers.
2738 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002739 QualType lhsType =
2740 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2741 QualType rhsType =
2742 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002743
Nate Begemanc5f0f652008-07-14 18:02:46 +00002744 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002745 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002746 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002747
Nate Begemanc5f0f652008-07-14 18:02:46 +00002748 // Handle the case of a vector & extvector type of the same size and element
2749 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002750 if (getLangOptions().LaxVectorConversions) {
2751 // FIXME: Should we warn here?
2752 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002753 if (const VectorType *RV = rhsType->getAsVectorType())
2754 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002755 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002756 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002757 }
2758 }
2759 }
2760
Nate Begemanc5f0f652008-07-14 18:02:46 +00002761 // If the lhs is an extended vector and the rhs is a scalar of the same type
2762 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002763 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002764 QualType eltType = V->getElementType();
2765
2766 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2767 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2768 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002769 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002770 return lhsType;
2771 }
2772 }
2773
Nate Begemanc5f0f652008-07-14 18:02:46 +00002774 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002775 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002776 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002777 QualType eltType = V->getElementType();
2778
2779 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2780 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2781 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002782 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002783 return rhsType;
2784 }
2785 }
2786
Chris Lattner4b009652007-07-25 00:24:17 +00002787 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002788 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002789 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002790 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002791 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002792}
2793
Chris Lattner4b009652007-07-25 00:24:17 +00002794inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002795 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002796{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002797 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002798 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002799
Steve Naroff8f708362007-08-24 19:07:16 +00002800 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002801
Chris Lattner4b009652007-07-25 00:24:17 +00002802 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002803 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002804 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002805}
2806
2807inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002808 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002809{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002810 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2811 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2812 return CheckVectorOperands(Loc, lex, rex);
2813 return InvalidOperands(Loc, lex, rex);
2814 }
Chris Lattner4b009652007-07-25 00:24:17 +00002815
Steve Naroff8f708362007-08-24 19:07:16 +00002816 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002817
Chris Lattner4b009652007-07-25 00:24:17 +00002818 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002819 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002820 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002821}
2822
2823inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002824 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002825{
2826 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002827 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002828
Steve Naroff8f708362007-08-24 19:07:16 +00002829 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002830
Chris Lattner4b009652007-07-25 00:24:17 +00002831 // handle the common case first (both operands are arithmetic).
2832 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002833 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002834
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002835 // Put any potential pointer into PExp
2836 Expr* PExp = lex, *IExp = rex;
2837 if (IExp->getType()->isPointerType())
2838 std::swap(PExp, IExp);
2839
2840 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2841 if (IExp->getType()->isIntegerType()) {
2842 // Check for arithmetic on pointers to incomplete types
2843 if (!PTy->getPointeeType()->isObjectType()) {
2844 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002845 if (getLangOptions().CPlusPlus) {
2846 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2847 << lex->getSourceRange() << rex->getSourceRange();
2848 return QualType();
2849 }
2850
2851 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002852 Diag(Loc, diag::ext_gnu_void_ptr)
2853 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002854 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002855 if (getLangOptions().CPlusPlus) {
2856 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2857 << lex->getType() << lex->getSourceRange();
2858 return QualType();
2859 }
2860
2861 // GNU extension: arithmetic on pointer to function
2862 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002863 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002864 } else {
2865 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2866 diag::err_typecheck_arithmetic_incomplete_type,
2867 lex->getSourceRange(), SourceRange(),
2868 lex->getType());
2869 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002870 }
2871 }
2872 return PExp->getType();
2873 }
2874 }
2875
Chris Lattner1eafdea2008-11-18 01:30:42 +00002876 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002877}
2878
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002879// C99 6.5.6
2880QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002881 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002882 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002883 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002884
Steve Naroff8f708362007-08-24 19:07:16 +00002885 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002886
Chris Lattnerf6da2912007-12-09 21:53:25 +00002887 // Enforce type constraints: C99 6.5.6p3.
2888
2889 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002890 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002891 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002892
2893 // Either ptr - int or ptr - ptr.
2894 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002895 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002896
Chris Lattnerf6da2912007-12-09 21:53:25 +00002897 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002898 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002899 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002900 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002901 Diag(Loc, diag::ext_gnu_void_ptr)
2902 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002903 } else if (lpointee->isFunctionType()) {
2904 if (getLangOptions().CPlusPlus) {
2905 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2906 << lex->getType() << lex->getSourceRange();
2907 return QualType();
2908 }
2909
2910 // GNU extension: arithmetic on pointer to function
2911 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2912 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002913 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002914 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002915 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002916 return QualType();
2917 }
2918 }
2919
2920 // The result type of a pointer-int computation is the pointer type.
2921 if (rex->getType()->isIntegerType())
2922 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002923
Chris Lattnerf6da2912007-12-09 21:53:25 +00002924 // Handle pointer-pointer subtractions.
2925 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002926 QualType rpointee = RHSPTy->getPointeeType();
2927
Chris Lattnerf6da2912007-12-09 21:53:25 +00002928 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002929 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002930 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002931 if (rpointee->isVoidType()) {
2932 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002933 Diag(Loc, diag::ext_gnu_void_ptr)
2934 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002935 } else if (rpointee->isFunctionType()) {
2936 if (getLangOptions().CPlusPlus) {
2937 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2938 << rex->getType() << rex->getSourceRange();
2939 return QualType();
2940 }
2941
2942 // GNU extension: arithmetic on pointer to function
2943 if (!lpointee->isFunctionType())
2944 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2945 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002946 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002947 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002948 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002949 return QualType();
2950 }
2951 }
2952
2953 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002954 if (!Context.typesAreCompatible(
2955 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2956 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002957 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002958 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002959 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002960 return QualType();
2961 }
2962
2963 return Context.getPointerDiffType();
2964 }
2965 }
2966
Chris Lattner1eafdea2008-11-18 01:30:42 +00002967 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002968}
2969
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002970// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002971QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002972 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002973 // C99 6.5.7p2: Each of the operands shall have integer type.
2974 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002975 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002976
Chris Lattner2c8bff72007-12-12 05:47:28 +00002977 // Shifts don't perform usual arithmetic conversions, they just do integer
2978 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002979 if (!isCompAssign)
2980 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002981 UsualUnaryConversions(rex);
2982
2983 // "The type of the result is that of the promoted left operand."
2984 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002985}
2986
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002987// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002988QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002989 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002990 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002991 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002992
Chris Lattner254f3bc2007-08-26 01:18:55 +00002993 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002994 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2995 UsualArithmeticConversions(lex, rex);
2996 else {
2997 UsualUnaryConversions(lex);
2998 UsualUnaryConversions(rex);
2999 }
Chris Lattner4b009652007-07-25 00:24:17 +00003000 QualType lType = lex->getType();
3001 QualType rType = rex->getType();
3002
Ted Kremenek486509e2007-10-29 17:13:39 +00003003 // For non-floating point types, check for self-comparisons of the form
3004 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3005 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003006 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003007 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3008 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003009 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003010 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003011 }
3012
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003013 // The result of comparisons is 'bool' in C++, 'int' in C.
3014 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3015
Chris Lattner254f3bc2007-08-26 01:18:55 +00003016 if (isRelational) {
3017 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003018 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003019 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003020 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003021 if (lType->isFloatingType()) {
3022 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003023 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003024 }
3025
Chris Lattner254f3bc2007-08-26 01:18:55 +00003026 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003027 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003028 }
Chris Lattner4b009652007-07-25 00:24:17 +00003029
Chris Lattner22be8422007-08-26 01:10:14 +00003030 bool LHSIsNull = lex->isNullPointerConstant(Context);
3031 bool RHSIsNull = rex->isNullPointerConstant(Context);
3032
Chris Lattner254f3bc2007-08-26 01:18:55 +00003033 // All of the following pointer related warnings are GCC extensions, except
3034 // when handling null pointer constants. One day, we can consider making them
3035 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003036 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003037 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003038 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003039 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003040 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003041
Steve Naroff3b435622007-11-13 14:57:38 +00003042 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003043 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3044 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003045 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003046 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003047 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003048 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003049 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003050 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003051 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003052 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003053 // Handle block pointer types.
3054 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3055 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3056 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3057
3058 if (!LHSIsNull && !RHSIsNull &&
3059 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003060 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003061 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003062 }
3063 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003064 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003065 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003066 // Allow block pointers to be compared with null pointer constants.
3067 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3068 (lType->isPointerType() && rType->isBlockPointerType())) {
3069 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003070 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003071 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003072 }
3073 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003074 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003075 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003076
Steve Naroff936c4362008-06-03 14:04:54 +00003077 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003078 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003079 const PointerType *LPT = lType->getAsPointerType();
3080 const PointerType *RPT = rType->getAsPointerType();
3081 bool LPtrToVoid = LPT ?
3082 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3083 bool RPtrToVoid = RPT ?
3084 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3085
3086 if (!LPtrToVoid && !RPtrToVoid &&
3087 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003088 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003089 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003090 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003091 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003092 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003093 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003094 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003095 }
Steve Naroff936c4362008-06-03 14:04:54 +00003096 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3097 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003098 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003099 } else {
3100 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003101 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003102 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003103 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003104 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003105 }
Steve Naroff936c4362008-06-03 14:04:54 +00003106 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003107 }
Steve Naroff936c4362008-06-03 14:04:54 +00003108 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3109 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003110 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003111 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003112 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003113 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003114 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003115 }
Steve Naroff936c4362008-06-03 14:04:54 +00003116 if (lType->isIntegerType() &&
3117 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003118 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003119 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003120 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003121 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003122 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003123 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003124 // Handle block pointers.
3125 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3126 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003127 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003128 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003129 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003130 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003131 }
3132 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3133 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003134 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003135 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003136 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003137 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003138 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003139 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003140}
3141
Nate Begemanc5f0f652008-07-14 18:02:46 +00003142/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3143/// operates on extended vector types. Instead of producing an IntTy result,
3144/// like a scalar comparison, a vector comparison produces a vector of integer
3145/// types.
3146QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003147 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003148 bool isRelational) {
3149 // Check to make sure we're operating on vectors of the same type and width,
3150 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003151 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003152 if (vType.isNull())
3153 return vType;
3154
3155 QualType lType = lex->getType();
3156 QualType rType = rex->getType();
3157
3158 // For non-floating point types, check for self-comparisons of the form
3159 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3160 // often indicate logic errors in the program.
3161 if (!lType->isFloatingType()) {
3162 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3163 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3164 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003165 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003166 }
3167
3168 // Check for comparisons of floating point operands using != and ==.
3169 if (!isRelational && lType->isFloatingType()) {
3170 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003171 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003172 }
3173
3174 // Return the type for the comparison, which is the same as vector type for
3175 // integer vectors, or an integer type of identical size and number of
3176 // elements for floating point vectors.
3177 if (lType->isIntegerType())
3178 return lType;
3179
3180 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003181 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003182 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003183 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003184 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3185 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3186
3187 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3188 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003189 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3190}
3191
Chris Lattner4b009652007-07-25 00:24:17 +00003192inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003193 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003194{
3195 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003196 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003197
Steve Naroff8f708362007-08-24 19:07:16 +00003198 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003199
3200 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003201 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003202 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003203}
3204
3205inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003206 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003207{
3208 UsualUnaryConversions(lex);
3209 UsualUnaryConversions(rex);
3210
Eli Friedmanbea3f842008-05-13 20:16:47 +00003211 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003212 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003213 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003214}
3215
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003216/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3217/// is a read-only property; return true if so. A readonly property expression
3218/// depends on various declarations and thus must be treated specially.
3219///
3220static bool IsReadonlyProperty(Expr *E, Sema &S)
3221{
3222 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3223 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3224 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3225 QualType BaseType = PropExpr->getBase()->getType();
3226 if (const PointerType *PTy = BaseType->getAsPointerType())
3227 if (const ObjCInterfaceType *IFTy =
3228 PTy->getPointeeType()->getAsObjCInterfaceType())
3229 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3230 if (S.isPropertyReadonly(PDecl, IFace))
3231 return true;
3232 }
3233 }
3234 return false;
3235}
3236
Chris Lattner4c2642c2008-11-18 01:22:49 +00003237/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3238/// emit an error and return true. If so, return false.
3239static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003240 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3241 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3242 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003243 if (IsLV == Expr::MLV_Valid)
3244 return false;
3245
3246 unsigned Diag = 0;
3247 bool NeedType = false;
3248 switch (IsLV) { // C99 6.5.16p2
3249 default: assert(0 && "Unknown result from isModifiableLvalue!");
3250 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003251 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003252 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3253 NeedType = true;
3254 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003255 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003256 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3257 NeedType = true;
3258 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003259 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003260 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3261 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003262 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003263 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3264 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003265 case Expr::MLV_IncompleteType:
3266 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003267 return S.DiagnoseIncompleteType(Loc, E->getType(),
3268 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3269 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003270 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003271 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3272 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003273 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003274 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3275 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003276 case Expr::MLV_ReadonlyProperty:
3277 Diag = diag::error_readonly_property_assignment;
3278 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003279 case Expr::MLV_NoSetterProperty:
3280 Diag = diag::error_nosetter_property_assignment;
3281 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003282 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003283
Chris Lattner4c2642c2008-11-18 01:22:49 +00003284 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003285 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003286 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003287 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003288 return true;
3289}
3290
3291
3292
3293// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003294QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3295 SourceLocation Loc,
3296 QualType CompoundType) {
3297 // Verify that LHS is a modifiable lvalue, and emit error if not.
3298 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003299 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003300
3301 QualType LHSType = LHS->getType();
3302 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003303
Chris Lattner005ed752008-01-04 18:04:52 +00003304 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003305 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003306 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003307 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003308 // Special case of NSObject attributes on c-style pointer types.
3309 if (ConvTy == IncompatiblePointer &&
3310 ((Context.isObjCNSObjectType(LHSType) &&
3311 Context.isObjCObjectPointerType(RHSType)) ||
3312 (Context.isObjCNSObjectType(RHSType) &&
3313 Context.isObjCObjectPointerType(LHSType))))
3314 ConvTy = Compatible;
3315
Chris Lattner34c85082008-08-21 18:04:13 +00003316 // If the RHS is a unary plus or minus, check to see if they = and + are
3317 // right next to each other. If so, the user may have typo'd "x =+ 4"
3318 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003319 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003320 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3321 RHSCheck = ICE->getSubExpr();
3322 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3323 if ((UO->getOpcode() == UnaryOperator::Plus ||
3324 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003325 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003326 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003327 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003328 Diag(Loc, diag::warn_not_compound_assign)
3329 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3330 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003331 }
3332 } else {
3333 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003334 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003335 }
Chris Lattner005ed752008-01-04 18:04:52 +00003336
Chris Lattner1eafdea2008-11-18 01:30:42 +00003337 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3338 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003339 return QualType();
3340
Chris Lattner4b009652007-07-25 00:24:17 +00003341 // C99 6.5.16p3: The type of an assignment expression is the type of the
3342 // left operand unless the left operand has qualified type, in which case
3343 // it is the unqualified version of the type of the left operand.
3344 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3345 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003346 // C++ 5.17p1: the type of the assignment expression is that of its left
3347 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003348 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003349}
3350
Chris Lattner1eafdea2008-11-18 01:30:42 +00003351// C99 6.5.17
3352QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3353 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003354
3355 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003356 DefaultFunctionArrayConversion(RHS);
3357 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003358}
3359
3360/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3361/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003362QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3363 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003364 QualType ResType = Op->getType();
3365 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003366
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003367 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3368 // Decrement of bool is not allowed.
3369 if (!isInc) {
3370 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3371 return QualType();
3372 }
3373 // Increment of bool sets it to true, but is deprecated.
3374 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3375 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003376 // OK!
3377 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3378 // C99 6.5.2.4p2, 6.5.6p2
3379 if (PT->getPointeeType()->isObjectType()) {
3380 // Pointer to object is ok!
3381 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003382 if (getLangOptions().CPlusPlus) {
3383 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3384 << Op->getSourceRange();
3385 return QualType();
3386 }
3387
3388 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003389 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003390 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003391 if (getLangOptions().CPlusPlus) {
3392 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3393 << Op->getType() << Op->getSourceRange();
3394 return QualType();
3395 }
3396
3397 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003398 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003399 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003400 } else {
3401 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3402 diag::err_typecheck_arithmetic_incomplete_type,
3403 Op->getSourceRange(), SourceRange(),
3404 ResType);
3405 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003406 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003407 } else if (ResType->isComplexType()) {
3408 // C99 does not support ++/-- on complex types, we allow as an extension.
3409 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003410 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003411 } else {
3412 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003413 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003414 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003415 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003416 // At this point, we know we have a real, complex or pointer type.
3417 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003418 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003419 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003420 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003421}
3422
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003423/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003424/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003425/// where the declaration is needed for type checking. We only need to
3426/// handle cases when the expression references a function designator
3427/// or is an lvalue. Here are some examples:
3428/// - &(x) => x
3429/// - &*****f => f for f a function designator.
3430/// - &s.xx => s
3431/// - &s.zz[1].yy -> s, if zz is an array
3432/// - *(x + 1) -> x, if x is an array
3433/// - &"123"[2] -> 0
3434/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003435static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003436 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003437 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003438 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003439 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003440 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003441 // Fields cannot be declared with a 'register' storage class.
3442 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003443 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003444 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003445 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003446 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003447 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003448
Douglas Gregord2baafd2008-10-21 16:13:35 +00003449 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003450 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003451 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003452 return 0;
3453 else
3454 return VD;
3455 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003456 case Stmt::UnaryOperatorClass: {
3457 UnaryOperator *UO = cast<UnaryOperator>(E);
3458
3459 switch(UO->getOpcode()) {
3460 case UnaryOperator::Deref: {
3461 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003462 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3463 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3464 if (!VD || VD->getType()->isPointerType())
3465 return 0;
3466 return VD;
3467 }
3468 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003469 }
3470 case UnaryOperator::Real:
3471 case UnaryOperator::Imag:
3472 case UnaryOperator::Extension:
3473 return getPrimaryDecl(UO->getSubExpr());
3474 default:
3475 return 0;
3476 }
3477 }
3478 case Stmt::BinaryOperatorClass: {
3479 BinaryOperator *BO = cast<BinaryOperator>(E);
3480
3481 // Handle cases involving pointer arithmetic. The result of an
3482 // Assign or AddAssign is not an lvalue so they can be ignored.
3483
3484 // (x + n) or (n + x) => x
3485 if (BO->getOpcode() == BinaryOperator::Add) {
3486 if (BO->getLHS()->getType()->isPointerType()) {
3487 return getPrimaryDecl(BO->getLHS());
3488 } else if (BO->getRHS()->getType()->isPointerType()) {
3489 return getPrimaryDecl(BO->getRHS());
3490 }
3491 }
3492
3493 return 0;
3494 }
Chris Lattner4b009652007-07-25 00:24:17 +00003495 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003496 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003497 case Stmt::ImplicitCastExprClass:
3498 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003499 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003500 default:
3501 return 0;
3502 }
3503}
3504
3505/// CheckAddressOfOperand - The operand of & must be either a function
3506/// designator or an lvalue designating an object. If it is an lvalue, the
3507/// object cannot be declared with storage class register or be a bit field.
3508/// Note: The usual conversions are *not* applied to the operand of the &
3509/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003510/// In C++, the operand might be an overloaded function name, in which case
3511/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003512QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003513 if (op->isTypeDependent())
3514 return Context.DependentTy;
3515
Steve Naroff9c6c3592008-01-13 17:10:08 +00003516 if (getLangOptions().C99) {
3517 // Implement C99-only parts of addressof rules.
3518 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3519 if (uOp->getOpcode() == UnaryOperator::Deref)
3520 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3521 // (assuming the deref expression is valid).
3522 return uOp->getSubExpr()->getType();
3523 }
3524 // Technically, there should be a check for array subscript
3525 // expressions here, but the result of one is always an lvalue anyway.
3526 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003527 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003528 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003529
Chris Lattner4b009652007-07-25 00:24:17 +00003530 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003531 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3532 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003533 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3534 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003535 return QualType();
3536 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003537 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003538 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3539 if (Field->isBitField()) {
3540 Diag(OpLoc, diag::err_typecheck_address_of)
3541 << "bit-field" << op->getSourceRange();
3542 return QualType();
3543 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003544 }
3545 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003546 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3547 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003548 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003549 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003550 return QualType();
3551 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003552 // We have an lvalue with a decl. Make sure the decl is not declared
3553 // with the register storage-class specifier.
3554 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3555 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003556 Diag(OpLoc, diag::err_typecheck_address_of)
3557 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003558 return QualType();
3559 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003560 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003561 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003562 } else if (isa<FieldDecl>(dcl)) {
3563 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003564 // Could be a pointer to member, though, if there is an explicit
3565 // scope qualifier for the class.
3566 if (isa<QualifiedDeclRefExpr>(op)) {
3567 DeclContext *Ctx = dcl->getDeclContext();
3568 if (Ctx && Ctx->isRecord())
3569 return Context.getMemberPointerType(op->getType(),
3570 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3571 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003572 } else if (isa<FunctionDecl>(dcl)) {
3573 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003574 // As above.
3575 if (isa<QualifiedDeclRefExpr>(op)) {
3576 DeclContext *Ctx = dcl->getDeclContext();
3577 if (Ctx && Ctx->isRecord())
3578 return Context.getMemberPointerType(op->getType(),
3579 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3580 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003581 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003582 else
Chris Lattner4b009652007-07-25 00:24:17 +00003583 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003584 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003585
Chris Lattner4b009652007-07-25 00:24:17 +00003586 // If the operand has type "type", the result has type "pointer to type".
3587 return Context.getPointerType(op->getType());
3588}
3589
Chris Lattnerda5c0872008-11-23 09:13:29 +00003590QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3591 UsualUnaryConversions(Op);
3592 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003593
Chris Lattnerda5c0872008-11-23 09:13:29 +00003594 // Note that per both C89 and C99, this is always legal, even if ptype is an
3595 // incomplete type or void. It would be possible to warn about dereferencing
3596 // a void pointer, but it's completely well-defined, and such a warning is
3597 // unlikely to catch any mistakes.
3598 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003599 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003600
Chris Lattner77d52da2008-11-20 06:06:08 +00003601 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003602 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003603 return QualType();
3604}
3605
3606static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3607 tok::TokenKind Kind) {
3608 BinaryOperator::Opcode Opc;
3609 switch (Kind) {
3610 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003611 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3612 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003613 case tok::star: Opc = BinaryOperator::Mul; break;
3614 case tok::slash: Opc = BinaryOperator::Div; break;
3615 case tok::percent: Opc = BinaryOperator::Rem; break;
3616 case tok::plus: Opc = BinaryOperator::Add; break;
3617 case tok::minus: Opc = BinaryOperator::Sub; break;
3618 case tok::lessless: Opc = BinaryOperator::Shl; break;
3619 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3620 case tok::lessequal: Opc = BinaryOperator::LE; break;
3621 case tok::less: Opc = BinaryOperator::LT; break;
3622 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3623 case tok::greater: Opc = BinaryOperator::GT; break;
3624 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3625 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3626 case tok::amp: Opc = BinaryOperator::And; break;
3627 case tok::caret: Opc = BinaryOperator::Xor; break;
3628 case tok::pipe: Opc = BinaryOperator::Or; break;
3629 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3630 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3631 case tok::equal: Opc = BinaryOperator::Assign; break;
3632 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3633 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3634 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3635 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3636 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3637 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3638 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3639 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3640 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3641 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3642 case tok::comma: Opc = BinaryOperator::Comma; break;
3643 }
3644 return Opc;
3645}
3646
3647static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3648 tok::TokenKind Kind) {
3649 UnaryOperator::Opcode Opc;
3650 switch (Kind) {
3651 default: assert(0 && "Unknown unary op!");
3652 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3653 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3654 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3655 case tok::star: Opc = UnaryOperator::Deref; break;
3656 case tok::plus: Opc = UnaryOperator::Plus; break;
3657 case tok::minus: Opc = UnaryOperator::Minus; break;
3658 case tok::tilde: Opc = UnaryOperator::Not; break;
3659 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003660 case tok::kw___real: Opc = UnaryOperator::Real; break;
3661 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3662 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3663 }
3664 return Opc;
3665}
3666
Douglas Gregord7f915e2008-11-06 23:29:22 +00003667/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3668/// operator @p Opc at location @c TokLoc. This routine only supports
3669/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003670Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3671 unsigned Op,
3672 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003673 QualType ResultTy; // Result type of the binary operator.
3674 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3675 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3676
3677 switch (Opc) {
3678 default:
3679 assert(0 && "Unknown binary expr!");
3680 case BinaryOperator::Assign:
3681 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3682 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003683 case BinaryOperator::PtrMemD:
3684 case BinaryOperator::PtrMemI:
3685 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3686 Opc == BinaryOperator::PtrMemI);
3687 break;
3688 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003689 case BinaryOperator::Div:
3690 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3691 break;
3692 case BinaryOperator::Rem:
3693 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3694 break;
3695 case BinaryOperator::Add:
3696 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3697 break;
3698 case BinaryOperator::Sub:
3699 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3700 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003701 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003702 case BinaryOperator::Shr:
3703 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3704 break;
3705 case BinaryOperator::LE:
3706 case BinaryOperator::LT:
3707 case BinaryOperator::GE:
3708 case BinaryOperator::GT:
3709 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3710 break;
3711 case BinaryOperator::EQ:
3712 case BinaryOperator::NE:
3713 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3714 break;
3715 case BinaryOperator::And:
3716 case BinaryOperator::Xor:
3717 case BinaryOperator::Or:
3718 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3719 break;
3720 case BinaryOperator::LAnd:
3721 case BinaryOperator::LOr:
3722 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3723 break;
3724 case BinaryOperator::MulAssign:
3725 case BinaryOperator::DivAssign:
3726 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3727 if (!CompTy.isNull())
3728 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3729 break;
3730 case BinaryOperator::RemAssign:
3731 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3732 if (!CompTy.isNull())
3733 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3734 break;
3735 case BinaryOperator::AddAssign:
3736 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3737 if (!CompTy.isNull())
3738 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3739 break;
3740 case BinaryOperator::SubAssign:
3741 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3742 if (!CompTy.isNull())
3743 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3744 break;
3745 case BinaryOperator::ShlAssign:
3746 case BinaryOperator::ShrAssign:
3747 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3748 if (!CompTy.isNull())
3749 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3750 break;
3751 case BinaryOperator::AndAssign:
3752 case BinaryOperator::XorAssign:
3753 case BinaryOperator::OrAssign:
3754 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3755 if (!CompTy.isNull())
3756 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3757 break;
3758 case BinaryOperator::Comma:
3759 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3760 break;
3761 }
3762 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003763 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003764 if (CompTy.isNull())
3765 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3766 else
3767 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003768 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003769}
3770
Chris Lattner4b009652007-07-25 00:24:17 +00003771// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003772Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3773 tok::TokenKind Kind,
3774 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003775 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003776 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003777
Steve Naroff87d58b42007-09-16 03:34:24 +00003778 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3779 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003780
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003781 // If either expression is type-dependent, just build the AST.
3782 // FIXME: We'll need to perform some caching of the result of name
3783 // lookup for operator+.
3784 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003785 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3786 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003787 Context.DependentTy,
3788 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003789 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003790 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3791 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003792 }
3793
Sebastian Redl95216a62009-02-07 00:15:38 +00003794 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003795 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3796 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003797 // If this is one of the assignment operators, we only perform
3798 // overload resolution if the left-hand side is a class or
3799 // enumeration type (C++ [expr.ass]p3).
3800 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3801 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3802 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3803 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003804
Douglas Gregord7f915e2008-11-06 23:29:22 +00003805 // Determine which overloaded operator we're dealing with.
3806 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003807 // Overloading .* is not possible.
3808 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003809 OO_Star, OO_Slash, OO_Percent,
3810 OO_Plus, OO_Minus,
3811 OO_LessLess, OO_GreaterGreater,
3812 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3813 OO_EqualEqual, OO_ExclaimEqual,
3814 OO_Amp,
3815 OO_Caret,
3816 OO_Pipe,
3817 OO_AmpAmp,
3818 OO_PipePipe,
3819 OO_Equal, OO_StarEqual,
3820 OO_SlashEqual, OO_PercentEqual,
3821 OO_PlusEqual, OO_MinusEqual,
3822 OO_LessLessEqual, OO_GreaterGreaterEqual,
3823 OO_AmpEqual, OO_CaretEqual,
3824 OO_PipeEqual,
3825 OO_Comma
3826 };
3827 OverloadedOperatorKind OverOp = OverOps[Opc];
3828
Douglas Gregor5ed15042008-11-18 23:14:02 +00003829 // Add the appropriate overloaded operators (C++ [over.match.oper])
3830 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003831 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003832 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003833 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3834 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003835
3836 // Perform overload resolution.
3837 OverloadCandidateSet::iterator Best;
3838 switch (BestViableFunction(CandidateSet, Best)) {
3839 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003840 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003841 FunctionDecl *FnDecl = Best->Function;
3842
Douglas Gregor70d26122008-11-12 17:17:38 +00003843 if (FnDecl) {
3844 // We matched an overloaded operator. Build a call to that
3845 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003846
Douglas Gregor70d26122008-11-12 17:17:38 +00003847 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003848 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3849 if (PerformObjectArgumentInitialization(lhs, Method) ||
3850 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3851 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003852 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003853 } else {
3854 // Convert the arguments.
3855 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3856 "passing") ||
3857 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3858 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003859 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003860 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003861
Douglas Gregor70d26122008-11-12 17:17:38 +00003862 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003863 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003864 = FnDecl->getType()->getAsFunctionType()->getResultType();
3865 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003866
Douglas Gregor70d26122008-11-12 17:17:38 +00003867 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003868 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3869 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003870 UsualUnaryConversions(FnExpr);
3871
Ted Kremenek362abcd2009-02-09 20:51:47 +00003872 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003873 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003874 } else {
3875 // We matched a built-in operator. Convert the arguments, then
3876 // break out so that we will build the appropriate built-in
3877 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003878 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3879 Best->Conversions[0], "passing") ||
3880 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3881 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003882 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003883
3884 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003885 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003886 }
3887
3888 case OR_No_Viable_Function:
3889 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003890 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003891 break;
3892
3893 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003894 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3895 << BinaryOperator::getOpcodeStr(Opc)
3896 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003897 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003898 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003899 }
3900
Douglas Gregor70d26122008-11-12 17:17:38 +00003901 // Either we found no viable overloaded operator or we matched a
3902 // built-in operator. In either case, fall through to trying to
3903 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003904 }
3905
Douglas Gregord7f915e2008-11-06 23:29:22 +00003906 // Build a built-in binary operation.
3907 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003908}
3909
3910// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003911Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3912 tok::TokenKind Op, ExprArg input) {
3913 // FIXME: Input is modified later, but smart pointer not reassigned.
3914 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003915 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003916
3917 if (getLangOptions().CPlusPlus &&
3918 (Input->getType()->isRecordType()
3919 || Input->getType()->isEnumeralType())) {
3920 // Determine which overloaded operator we're dealing with.
3921 static const OverloadedOperatorKind OverOps[] = {
3922 OO_None, OO_None,
3923 OO_PlusPlus, OO_MinusMinus,
3924 OO_Amp, OO_Star,
3925 OO_Plus, OO_Minus,
3926 OO_Tilde, OO_Exclaim,
3927 OO_None, OO_None,
3928 OO_None,
3929 OO_None
3930 };
3931 OverloadedOperatorKind OverOp = OverOps[Opc];
3932
3933 // Add the appropriate overloaded operators (C++ [over.match.oper])
3934 // to the candidate set.
3935 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003936 if (OverOp != OO_None &&
3937 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3938 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003939
3940 // Perform overload resolution.
3941 OverloadCandidateSet::iterator Best;
3942 switch (BestViableFunction(CandidateSet, Best)) {
3943 case OR_Success: {
3944 // We found a built-in operator or an overloaded operator.
3945 FunctionDecl *FnDecl = Best->Function;
3946
3947 if (FnDecl) {
3948 // We matched an overloaded operator. Build a call to that
3949 // operator.
3950
3951 // Convert the arguments.
3952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3953 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003954 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003955 } else {
3956 // Convert the arguments.
3957 if (PerformCopyInitialization(Input,
3958 FnDecl->getParamDecl(0)->getType(),
3959 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003960 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003961 }
3962
3963 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003964 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003965 = FnDecl->getType()->getAsFunctionType()->getResultType();
3966 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003967
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003968 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003969 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3970 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003971 UsualUnaryConversions(FnExpr);
3972
Sebastian Redl8b769972009-01-19 00:08:26 +00003973 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003974 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003975 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003976 } else {
3977 // We matched a built-in operator. Convert the arguments, then
3978 // break out so that we will build the appropriate built-in
3979 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003980 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3981 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003982 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003983
3984 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003985 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003986 }
3987
3988 case OR_No_Viable_Function:
3989 // No viable function; fall through to handling this as a
3990 // built-in operator, which will produce an error message for us.
3991 break;
3992
3993 case OR_Ambiguous:
3994 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3995 << UnaryOperator::getOpcodeStr(Opc)
3996 << Input->getSourceRange();
3997 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003998 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003999 }
4000
4001 // Either we found no viable overloaded operator or we matched a
4002 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004003 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004004 }
4005
Chris Lattner4b009652007-07-25 00:24:17 +00004006 QualType resultType;
4007 switch (Opc) {
4008 default:
4009 assert(0 && "Unimplemented unary expr!");
4010 case UnaryOperator::PreInc:
4011 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004012 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4013 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004014 break;
4015 case UnaryOperator::AddrOf:
4016 resultType = CheckAddressOfOperand(Input, OpLoc);
4017 break;
4018 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004019 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004020 resultType = CheckIndirectionOperand(Input, OpLoc);
4021 break;
4022 case UnaryOperator::Plus:
4023 case UnaryOperator::Minus:
4024 UsualUnaryConversions(Input);
4025 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004026 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4027 break;
4028 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4029 resultType->isEnumeralType())
4030 break;
4031 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4032 Opc == UnaryOperator::Plus &&
4033 resultType->isPointerType())
4034 break;
4035
Sebastian Redl8b769972009-01-19 00:08:26 +00004036 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4037 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004038 case UnaryOperator::Not: // bitwise complement
4039 UsualUnaryConversions(Input);
4040 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004041 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4042 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4043 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004044 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004045 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004046 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004047 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4048 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004049 break;
4050 case UnaryOperator::LNot: // logical negation
4051 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4052 DefaultFunctionArrayConversion(Input);
4053 resultType = Input->getType();
4054 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004055 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4056 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004057 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004058 // In C++, it's bool. C++ 5.3.1p8
4059 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004060 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004061 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004062 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004063 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004064 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004065 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004066 resultType = Input->getType();
4067 break;
4068 }
4069 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004070 return ExprError();
4071 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004072 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004073}
4074
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004075/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4076Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004077 SourceLocation LabLoc,
4078 IdentifierInfo *LabelII) {
4079 // Look up the record for this label identifier.
4080 LabelStmt *&LabelDecl = LabelMap[LabelII];
4081
Daniel Dunbar879788d2008-08-04 16:51:22 +00004082 // If we haven't seen this label yet, create a forward reference. It
4083 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004084 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004085 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004086
4087 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004088 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4089 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004090}
4091
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004092Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004093 SourceLocation RPLoc) { // "({..})"
4094 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4095 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4096 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4097
Eli Friedmanbc941e12009-01-24 23:09:00 +00004098 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4099 if (isFileScope) {
4100 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4101 }
4102
Chris Lattner4b009652007-07-25 00:24:17 +00004103 // FIXME: there are a variety of strange constraints to enforce here, for
4104 // example, it is not possible to goto into a stmt expression apparently.
4105 // More semantic analysis is needed.
4106
4107 // FIXME: the last statement in the compount stmt has its value used. We
4108 // should not warn about it being unused.
4109
4110 // If there are sub stmts in the compound stmt, take the type of the last one
4111 // as the type of the stmtexpr.
4112 QualType Ty = Context.VoidTy;
4113
Chris Lattner200964f2008-07-26 19:51:01 +00004114 if (!Compound->body_empty()) {
4115 Stmt *LastStmt = Compound->body_back();
4116 // If LastStmt is a label, skip down through into the body.
4117 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4118 LastStmt = Label->getSubStmt();
4119
4120 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004121 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004122 }
Chris Lattner4b009652007-07-25 00:24:17 +00004123
Steve Naroff774e4152009-01-21 00:14:39 +00004124 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004125}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004126
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004127Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4128 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004129 SourceLocation TypeLoc,
4130 TypeTy *argty,
4131 OffsetOfComponent *CompPtr,
4132 unsigned NumComponents,
4133 SourceLocation RPLoc) {
4134 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4135 assert(!ArgTy.isNull() && "Missing type argument!");
4136
4137 // We must have at least one component that refers to the type, and the first
4138 // one is known to be a field designator. Verify that the ArgTy represents
4139 // a struct/union/class.
4140 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004141 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004142
4143 // Otherwise, create a compound literal expression as the base, and
4144 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004145 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004146 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004147 IList->setType(ArgTy);
4148 Expr *Res =
4149 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4150
Chris Lattnerb37522e2007-08-31 21:49:13 +00004151 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4152 // GCC extension, diagnose them.
4153 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004154 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4155 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004156
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004157 for (unsigned i = 0; i != NumComponents; ++i) {
4158 const OffsetOfComponent &OC = CompPtr[i];
4159 if (OC.isBrackets) {
4160 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004161 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004162 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004163 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004164 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004165 }
4166
Chris Lattner2af6a802007-08-30 17:59:59 +00004167 // FIXME: C++: Verify that operator[] isn't overloaded.
4168
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004169 // C99 6.5.2.1p1
4170 Expr *Idx = static_cast<Expr*>(OC.U.E);
4171 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004172 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4173 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004174
Steve Naroff774e4152009-01-21 00:14:39 +00004175 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4176 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004177 continue;
4178 }
4179
4180 const RecordType *RC = Res->getType()->getAsRecordType();
4181 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004182 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004183 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004184 }
4185
4186 // Get the decl corresponding to this.
4187 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004188 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004189 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4190 LookupMemberName)
4191 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004192 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004193 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4194 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004195
4196 // FIXME: C++: Verify that MemberDecl isn't a static field.
4197 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004198 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4199 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004200 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4201 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004202 }
4203
Steve Naroff774e4152009-01-21 00:14:39 +00004204 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4205 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004206}
4207
4208
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004209Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004210 TypeTy *arg1, TypeTy *arg2,
4211 SourceLocation RPLoc) {
4212 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4213 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4214
4215 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4216
Steve Naroff774e4152009-01-21 00:14:39 +00004217 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4218 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004219}
4220
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004221Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004222 ExprTy *expr1, ExprTy *expr2,
4223 SourceLocation RPLoc) {
4224 Expr *CondExpr = static_cast<Expr*>(cond);
4225 Expr *LHSExpr = static_cast<Expr*>(expr1);
4226 Expr *RHSExpr = static_cast<Expr*>(expr2);
4227
4228 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4229
4230 // The conditional expression is required to be a constant expression.
4231 llvm::APSInt condEval(32);
4232 SourceLocation ExpLoc;
4233 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004234 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4235 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004236
4237 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4238 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4239 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004240 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4241 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004242}
4243
Steve Naroff52a81c02008-09-03 18:15:37 +00004244//===----------------------------------------------------------------------===//
4245// Clang Extensions.
4246//===----------------------------------------------------------------------===//
4247
4248/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004249void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004250 // Analyze block parameters.
4251 BlockSemaInfo *BSI = new BlockSemaInfo();
4252
4253 // Add BSI to CurBlock.
4254 BSI->PrevBlockInfo = CurBlock;
4255 CurBlock = BSI;
4256
4257 BSI->ReturnType = 0;
4258 BSI->TheScope = BlockScope;
4259
Steve Naroff52059382008-10-10 01:28:17 +00004260 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004261 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004262}
4263
Mike Stumpc1fddff2009-02-04 22:31:32 +00004264void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4265 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4266
4267 if (ParamInfo.getNumTypeObjects() == 0
4268 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4269 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4270
4271 // The type is entirely optional as well, if none, use DependentTy.
4272 if (T.isNull())
4273 T = Context.DependentTy;
4274
4275 // The parameter list is optional, if there was none, assume ().
4276 if (!T->isFunctionType())
4277 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4278
4279 CurBlock->hasPrototype = true;
4280 CurBlock->isVariadic = false;
4281 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4282 .getTypePtr();
4283
4284 if (!RetTy->isDependentType())
4285 CurBlock->ReturnType = RetTy;
4286 return;
4287 }
4288
Steve Naroff52a81c02008-09-03 18:15:37 +00004289 // Analyze arguments to block.
4290 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4291 "Not a function declarator!");
4292 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004293
Steve Naroff52059382008-10-10 01:28:17 +00004294 CurBlock->hasPrototype = FTI.hasPrototype;
4295 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004296
4297 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4298 // no arguments, not a function that takes a single void argument.
4299 if (FTI.hasPrototype &&
4300 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4301 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4302 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4303 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004304 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004305 } else if (FTI.hasPrototype) {
4306 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004307 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4308 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004309 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4310
4311 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4312 .getTypePtr();
4313
4314 if (!RetTy->isDependentType())
4315 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004316 }
Steve Naroff52059382008-10-10 01:28:17 +00004317 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4318
4319 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4320 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4321 // If this has an identifier, add it to the scope stack.
4322 if ((*AI)->getIdentifier())
4323 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004324}
4325
4326/// ActOnBlockError - If there is an error parsing a block, this callback
4327/// is invoked to pop the information about the block from the action impl.
4328void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4329 // Ensure that CurBlock is deleted.
4330 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4331
4332 // Pop off CurBlock, handle nested blocks.
4333 CurBlock = CurBlock->PrevBlockInfo;
4334
4335 // FIXME: Delete the ParmVarDecl objects as well???
4336
4337}
4338
4339/// ActOnBlockStmtExpr - This is called when the body of a block statement
4340/// literal was successfully completed. ^(int x){...}
4341Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4342 Scope *CurScope) {
4343 // Ensure that CurBlock is deleted.
4344 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004345 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004346
Steve Naroff52059382008-10-10 01:28:17 +00004347 PopDeclContext();
4348
Steve Naroff52a81c02008-09-03 18:15:37 +00004349 // Pop off CurBlock, handle nested blocks.
4350 CurBlock = CurBlock->PrevBlockInfo;
4351
4352 QualType RetTy = Context.VoidTy;
4353 if (BSI->ReturnType)
4354 RetTy = QualType(BSI->ReturnType, 0);
4355
4356 llvm::SmallVector<QualType, 8> ArgTypes;
4357 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4358 ArgTypes.push_back(BSI->Params[i]->getType());
4359
4360 QualType BlockTy;
4361 if (!BSI->hasPrototype)
4362 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4363 else
4364 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004365 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004366
4367 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004368
Steve Naroff95029d92008-10-08 18:44:00 +00004369 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004370 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004371}
4372
Nate Begemanbd881ef2008-01-30 20:50:20 +00004373/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004374/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004375/// The number of arguments has already been validated to match the number of
4376/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004377static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4378 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004379 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004380 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004381 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4382 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004383
4384 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004385 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004386 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004387 return true;
4388}
4389
4390Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4391 SourceLocation *CommaLocs,
4392 SourceLocation BuiltinLoc,
4393 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004394 // __builtin_overload requires at least 2 arguments
4395 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004396 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4397 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004398
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004399 // The first argument is required to be a constant expression. It tells us
4400 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004401 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004402 Expr *NParamsExpr = Args[0];
4403 llvm::APSInt constEval(32);
4404 SourceLocation ExpLoc;
4405 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004406 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4407 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004408
4409 // Verify that the number of parameters is > 0
4410 unsigned NumParams = constEval.getZExtValue();
4411 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004412 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4413 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004414 // Verify that we have at least 1 + NumParams arguments to the builtin.
4415 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004416 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4417 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004418
4419 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004420 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004421 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004422 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4423 // UsualUnaryConversions will convert the function DeclRefExpr into a
4424 // pointer to function.
4425 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004426 const FunctionTypeProto *FnType = 0;
4427 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4428 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004429
4430 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4431 // parameters, and the number of parameters must match the value passed to
4432 // the builtin.
4433 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004434 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4435 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004436
4437 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004438 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004439 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004440 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004441 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004442 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4443 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004444 // Remember our match, and continue processing the remaining arguments
4445 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004446 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004447 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004448 BuiltinLoc, RParenLoc);
4449 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004450 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004451 // Return the newly created OverloadExpr node, if we succeded in matching
4452 // exactly one of the candidate functions.
4453 if (OE)
4454 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004455
4456 // If we didn't find a matching function Expr in the __builtin_overload list
4457 // the return an error.
4458 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004459 for (unsigned i = 0; i != NumParams; ++i) {
4460 if (i != 0) typeNames += ", ";
4461 typeNames += Args[i+1]->getType().getAsString();
4462 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004463
Chris Lattner77d52da2008-11-20 06:06:08 +00004464 return Diag(BuiltinLoc, diag::err_overload_no_match)
4465 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004466}
4467
Anders Carlsson36760332007-10-15 20:28:48 +00004468Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4469 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004470 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004471 Expr *E = static_cast<Expr*>(expr);
4472 QualType T = QualType::getFromOpaquePtr(type);
4473
4474 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004475
4476 // Get the va_list type
4477 QualType VaListType = Context.getBuiltinVaListType();
4478 // Deal with implicit array decay; for example, on x86-64,
4479 // va_list is an array, but it's supposed to decay to
4480 // a pointer for va_arg.
4481 if (VaListType->isArrayType())
4482 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004483 // Make sure the input expression also decays appropriately.
4484 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004485
4486 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004487 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004488 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004489 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004490
4491 // FIXME: Warn if a non-POD type is passed in.
4492
Steve Naroff774e4152009-01-21 00:14:39 +00004493 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004494}
4495
Douglas Gregorad4b3792008-11-29 04:51:27 +00004496Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4497 // The type of __null will be int or long, depending on the size of
4498 // pointers on the target.
4499 QualType Ty;
4500 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4501 Ty = Context.IntTy;
4502 else
4503 Ty = Context.LongTy;
4504
Steve Naroff774e4152009-01-21 00:14:39 +00004505 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004506}
4507
Chris Lattner005ed752008-01-04 18:04:52 +00004508bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4509 SourceLocation Loc,
4510 QualType DstType, QualType SrcType,
4511 Expr *SrcExpr, const char *Flavor) {
4512 // Decode the result (notice that AST's are still created for extensions).
4513 bool isInvalid = false;
4514 unsigned DiagKind;
4515 switch (ConvTy) {
4516 default: assert(0 && "Unknown conversion type");
4517 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004518 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004519 DiagKind = diag::ext_typecheck_convert_pointer_int;
4520 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004521 case IntToPointer:
4522 DiagKind = diag::ext_typecheck_convert_int_pointer;
4523 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004524 case IncompatiblePointer:
4525 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4526 break;
4527 case FunctionVoidPointer:
4528 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4529 break;
4530 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004531 // If the qualifiers lost were because we were applying the
4532 // (deprecated) C++ conversion from a string literal to a char*
4533 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4534 // Ideally, this check would be performed in
4535 // CheckPointerTypesForAssignment. However, that would require a
4536 // bit of refactoring (so that the second argument is an
4537 // expression, rather than a type), which should be done as part
4538 // of a larger effort to fix CheckPointerTypesForAssignment for
4539 // C++ semantics.
4540 if (getLangOptions().CPlusPlus &&
4541 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4542 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004543 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4544 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004545 case IntToBlockPointer:
4546 DiagKind = diag::err_int_to_block_pointer;
4547 break;
4548 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004549 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004550 break;
Steve Naroff19608432008-10-14 22:18:38 +00004551 case IncompatibleObjCQualifiedId:
4552 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4553 // it can give a more specific diagnostic.
4554 DiagKind = diag::warn_incompatible_qualified_id;
4555 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004556 case IncompatibleVectors:
4557 DiagKind = diag::warn_incompatible_vectors;
4558 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004559 case Incompatible:
4560 DiagKind = diag::err_typecheck_convert_incompatible;
4561 isInvalid = true;
4562 break;
4563 }
4564
Chris Lattner271d4c22008-11-24 05:29:24 +00004565 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4566 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004567 return isInvalid;
4568}
Anders Carlssond5201b92008-11-30 19:50:32 +00004569
4570bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4571{
4572 Expr::EvalResult EvalResult;
4573
4574 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4575 EvalResult.HasSideEffects) {
4576 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4577
4578 if (EvalResult.Diag) {
4579 // We only show the note if it's not the usual "invalid subexpression"
4580 // or if it's actually in a subexpression.
4581 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4582 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4583 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4584 }
4585
4586 return true;
4587 }
4588
4589 if (EvalResult.Diag) {
4590 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4591 E->getSourceRange();
4592
4593 // Print the reason it's not a constant.
4594 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4595 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4596 }
4597
4598 if (Result)
4599 *Result = EvalResult.Val.getInt();
4600 return false;
4601}