blob: 705fe4dfeef3caecae1eb96c6dd274527b819d59 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor48f3bb92009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerf15970c2009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62 MD->isInstanceMethod());
63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner76a642f2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregor48f3bb92009-02-18 21:56:37 +000072 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000074 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000079 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
82 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner76a642f2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregor48f3bb92009-02-18 21:56:37 +000087 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000088}
89
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000090SourceRange Sema::getExprRange(ExprTy *E) const {
91 Expr *Ex = (Expr *)E;
92 return Ex? Ex->getSourceRange() : SourceRange();
93}
94
Chris Lattnere7a2e912008-07-25 21:10:04 +000095//===----------------------------------------------------------------------===//
96// Standard Promotions and Conversions
97//===----------------------------------------------------------------------===//
98
Chris Lattnere7a2e912008-07-25 21:10:04 +000099/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
100void Sema::DefaultFunctionArrayConversion(Expr *&E) {
101 QualType Ty = E->getType();
102 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
103
Chris Lattnere7a2e912008-07-25 21:10:04 +0000104 if (Ty->isFunctionType())
105 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +0000106 else if (Ty->isArrayType()) {
107 // In C90 mode, arrays only promote to pointers if the array expression is
108 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
109 // type 'array of type' is converted to an expression that has type 'pointer
110 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
111 // that has type 'array of type' ...". The relevant change is "an lvalue"
112 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000113 //
114 // C++ 4.2p1:
115 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
116 // T" can be converted to an rvalue of type "pointer to T".
117 //
118 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
119 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +0000120 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
121 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000122}
123
124/// UsualUnaryConversions - Performs various conversions that are common to most
125/// operators (C99 6.3). The conversions of array and function types are
126/// sometimes surpressed. For example, the array->pointer conversion doesn't
127/// apply if the array is an argument to the sizeof or address (&) operators.
128/// In these instances, this routine should *not* be called.
129Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
130 QualType Ty = Expr->getType();
131 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
132
Chris Lattnere7a2e912008-07-25 21:10:04 +0000133 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
134 ImpCastExprToType(Expr, Context.IntTy);
135 else
136 DefaultFunctionArrayConversion(Expr);
137
138 return Expr;
139}
140
Chris Lattner05faf172008-07-25 22:25:12 +0000141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
142/// do not have a prototype. Arguments that have type float are promoted to
143/// double. All other argument types are converted by UsualUnaryConversions().
144void Sema::DefaultArgumentPromotion(Expr *&Expr) {
145 QualType Ty = Expr->getType();
146 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
147
148 // If this is a 'float' (CVR qualified or typedef) promote to double.
149 if (const BuiltinType *BT = Ty->getAsBuiltinType())
150 if (BT->getKind() == BuiltinType::Float)
151 return ImpCastExprToType(Expr, Context.DoubleTy);
152
153 UsualUnaryConversions(Expr);
154}
155
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
157// will warn if the resulting type is not a POD type.
Chris Lattner76a642f2009-02-15 22:43:40 +0000158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000159 DefaultArgumentPromotion(Expr);
160
161 if (!Expr->getType()->isPODType()) {
162 Diag(Expr->getLocStart(),
163 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
164 Expr->getType() << CT;
165 }
166}
167
168
Chris Lattnere7a2e912008-07-25 21:10:04 +0000169/// UsualArithmeticConversions - Performs various conversions that are common to
170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
171/// routine returns the first non-arithmetic type found. The client is
172/// responsible for emitting appropriate error diagnostics.
173/// FIXME: verify the conversion rules for "complex int" are consistent with
174/// GCC.
175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
176 bool isCompAssign) {
177 if (!isCompAssign) {
178 UsualUnaryConversions(lhsExpr);
179 UsualUnaryConversions(rhsExpr);
180 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000181
Chris Lattnere7a2e912008-07-25 21:10:04 +0000182 // For conversion purposes, we ignore any qualifiers.
183 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000184 QualType lhs =
185 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
186 QualType rhs =
187 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000188
189 // If both types are identical, no conversion is needed.
190 if (lhs == rhs)
191 return lhs;
192
193 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
194 // The caller can deal with this (e.g. pointer + int).
195 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
196 return lhs;
197
198 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
199 if (!isCompAssign) {
200 ImpCastExprToType(lhsExpr, destType);
201 ImpCastExprToType(rhsExpr, destType);
202 }
203 return destType;
204}
205
206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
207 // Perform the usual unary conversions. We do this early so that
208 // integral promotions to "int" can allow us to exit early, in the
209 // lhs == rhs check. Also, for conversion purposes, we ignore any
210 // qualifiers. For example, "const float" and "float" are
211 // equivalent.
Chris Lattner76a642f2009-02-15 22:43:40 +0000212 if (lhs->isPromotableIntegerType())
213 lhs = Context.IntTy;
214 else
215 lhs = lhs.getUnqualifiedType();
216 if (rhs->isPromotableIntegerType())
217 rhs = Context.IntTy;
218 else
219 rhs = rhs.getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000220
Chris Lattnere7a2e912008-07-25 21:10:04 +0000221 // If both types are identical, no conversion is needed.
222 if (lhs == rhs)
223 return lhs;
224
225 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
226 // The caller can deal with this (e.g. pointer + int).
227 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
228 return lhs;
229
230 // At this point, we have two different arithmetic types.
231
232 // Handle complex types first (C99 6.3.1.8p1).
233 if (lhs->isComplexType() || rhs->isComplexType()) {
234 // if we have an integer operand, the result is the complex type.
235 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
236 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237 return lhs;
238 }
239 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
240 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000241 return rhs;
242 }
243 // This handles complex/complex, complex/float, or float/complex.
244 // When both operands are complex, the shorter operand is converted to the
245 // type of the longer, and that is the type of the result. This corresponds
246 // to what is done when combining two real floating-point operands.
247 // The fun begins when size promotion occur across type domains.
248 // From H&S 6.3.4: When one operand is complex and the other is a real
249 // floating-point type, the less precise type is converted, within it's
250 // real or complex domain, to the precision of the other type. For example,
251 // when combining a "long double" with a "double _Complex", the
252 // "double _Complex" is promoted to "long double _Complex".
253 int result = Context.getFloatingTypeOrder(lhs, rhs);
254
255 if (result > 0) { // The left side is bigger, convert rhs.
256 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000257 } else if (result < 0) { // The right side is bigger, convert lhs.
258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000259 }
260 // At this point, lhs and rhs have the same rank/size. Now, make sure the
261 // domains match. This is a requirement for our implementation, C99
262 // does not require this promotion.
263 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
264 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000265 return rhs;
266 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000267 return lhs;
268 }
269 }
270 return lhs; // The domain/size match exactly.
271 }
272 // Now handle "real" floating types (i.e. float, double, long double).
273 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
274 // if we have an integer operand, the result is the real floating type.
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000275 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000276 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000277 return lhs;
278 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000279 if (rhs->isComplexIntegerType()) {
280 // convert rhs to the complex floating point type.
281 return Context.getComplexType(lhs);
282 }
283 if (lhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000284 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000285 return rhs;
286 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000287 if (lhs->isComplexIntegerType()) {
288 // convert lhs to the complex floating point type.
289 return Context.getComplexType(rhs);
290 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000291 // We have two real floating types, float/complex combos were handled above.
292 // Convert the smaller operand to the bigger result.
293 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner76a642f2009-02-15 22:43:40 +0000294 if (result > 0) // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000295 return lhs;
Chris Lattner76a642f2009-02-15 22:43:40 +0000296 assert(result < 0 && "illegal float comparison");
297 return rhs; // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000298 }
299 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
300 // Handle GCC complex int extension.
301 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
302 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
303
304 if (lhsComplexInt && rhsComplexInt) {
305 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner76a642f2009-02-15 22:43:40 +0000306 rhsComplexInt->getElementType()) >= 0)
307 return lhs; // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000308 return rhs;
309 } else if (lhsComplexInt && rhs->isIntegerType()) {
310 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000311 return lhs;
312 } else if (rhsComplexInt && lhs->isIntegerType()) {
313 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000314 return rhs;
315 }
316 }
317 // Finally, we have two differing integer types.
318 // The rules for this case are in C99 6.3.1.8
319 int compare = Context.getIntegerTypeOrder(lhs, rhs);
320 bool lhsSigned = lhs->isSignedIntegerType(),
321 rhsSigned = rhs->isSignedIntegerType();
322 QualType destType;
323 if (lhsSigned == rhsSigned) {
324 // Same signedness; use the higher-ranked type
325 destType = compare >= 0 ? lhs : rhs;
326 } else if (compare != (lhsSigned ? 1 : -1)) {
327 // The unsigned type has greater than or equal rank to the
328 // signed type, so use the unsigned type
329 destType = lhsSigned ? rhs : lhs;
330 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
331 // The two types are different widths; if we are here, that
332 // means the signed type is larger than the unsigned type, so
333 // use the signed type.
334 destType = lhsSigned ? lhs : rhs;
335 } else {
336 // The signed type is higher-ranked than the unsigned type,
337 // but isn't actually any bigger (like unsigned int and long
338 // on most 32-bit systems). Use the unsigned type corresponding
339 // to the signed type.
340 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
341 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000342 return destType;
343}
344
345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Narofff69936d2007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000362 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000363
364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000367
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373 if (getLangOptions().CPlusPlus)
374 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000375
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Chris Lattner726e1682009-02-18 05:49:11 +0000382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattner2085fd62009-02-18 06:40:38 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
Chris Lattner639e2d32008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
396/// FIXME: This will create BlockDeclRefExprs for global variables,
397/// function references, etc which is suboptimal :) and breaks
398/// things like "integer constant expression" tests.
399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
405
406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
414 return Var->hasLocalStorage();
415
416 return true;
417}
418
419
420
Steve Naroff08d92e42007-09-15 18:49:24 +0000421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000423/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000425/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427 IdentifierInfo &II,
428 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000429 const CXXScopeSpec *SS,
430 bool isAddressOfOperand) {
431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor17330012009-02-04 15:01:18 +0000432 isAddressOfOperand);
Douglas Gregor10c42622008-11-18 15:03:34 +0000433}
434
Douglas Gregor1a49af92009-01-06 05:10:23 +0000435/// BuildDeclRefExpr - Build either a DeclRefExpr or a
436/// QualifiedDeclRefExpr based on whether or not SS is a
437/// nested-name-specifier.
Sebastian Redlebc07d52009-02-03 20:19:35 +0000438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440 bool TypeDependent, bool ValueDependent,
441 const CXXScopeSpec *SS) {
Douglas Gregorbad35182009-03-19 03:51:16 +0000442 if (SS && !SS->isEmpty()) {
443 llvm::SmallVector<NestedNameSpecifier, 16> Specs;
444 for (CXXScopeSpec::iterator Spec = SS->begin(), SpecEnd = SS->end();
445 Spec != SpecEnd; ++Spec)
446 Specs.push_back(NestedNameSpecifier::getFromOpaquePtr(*Spec));
447 return QualifiedDeclRefExpr::Create(Context, D, Ty, Loc, TypeDependent,
448 ValueDependent, SS->getRange(),
449 &Specs[0], Specs.size());
450 } else
Steve Naroff6ece14c2009-01-21 00:14:39 +0000451 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000452}
453
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000454/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
455/// variable corresponding to the anonymous union or struct whose type
456/// is Record.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000457static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000458 assert(Record->isAnonymousStructOrUnion() &&
459 "Record must be an anonymous struct or union!");
460
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000461 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000462 // be an O(1) operation rather than a slow walk through DeclContext's
463 // vector (which itself will be eliminated). DeclGroups might make
464 // this even better.
465 DeclContext *Ctx = Record->getDeclContext();
466 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
467 DEnd = Ctx->decls_end();
468 D != DEnd; ++D) {
469 if (*D == Record) {
470 // The object for the anonymous struct/union directly
471 // follows its type in the list of declarations.
472 ++D;
473 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000474 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000475 return *D;
476 }
477 }
478
479 assert(false && "Missing object for anonymous record");
480 return 0;
481}
482
Sebastian Redlcd965b92009-01-18 18:53:16 +0000483Sema::OwningExprResult
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000484Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
485 FieldDecl *Field,
486 Expr *BaseObjectExpr,
487 SourceLocation OpLoc) {
488 assert(Field->getDeclContext()->isRecord() &&
489 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
490 && "Field must be stored inside an anonymous struct or union");
491
492 // Construct the sequence of field member references
493 // we'll have to perform to get to the field in the anonymous
494 // union/struct. The list of members is built from the field
495 // outward, so traverse it backwards to go from an object in
496 // the current context to the field we found.
497 llvm::SmallVector<FieldDecl *, 4> AnonFields;
498 AnonFields.push_back(Field);
499 VarDecl *BaseObject = 0;
500 DeclContext *Ctx = Field->getDeclContext();
501 do {
502 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000503 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000504 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
505 AnonFields.push_back(AnonField);
506 else {
507 BaseObject = cast<VarDecl>(AnonObject);
508 break;
509 }
510 Ctx = Ctx->getParent();
511 } while (Ctx->isRecord() &&
512 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
513
514 // Build the expression that refers to the base object, from
515 // which we will build a sequence of member references to each
516 // of the anonymous union objects and, eventually, the field we
517 // found via name lookup.
518 bool BaseObjectIsPointer = false;
519 unsigned ExtraQuals = 0;
520 if (BaseObject) {
521 // BaseObject is an anonymous struct/union variable (and is,
522 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000523 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000524 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000525 SourceLocation());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000526 ExtraQuals
527 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
528 } else if (BaseObjectExpr) {
529 // The caller provided the base object expression. Determine
530 // whether its a pointer and whether it adds any qualifiers to the
531 // anonymous struct/union fields we're looking into.
532 QualType ObjectType = BaseObjectExpr->getType();
533 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
534 BaseObjectIsPointer = true;
535 ObjectType = ObjectPtr->getPointeeType();
536 }
537 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
538 } else {
539 // We've found a member of an anonymous struct/union that is
540 // inside a non-anonymous struct/union, so in a well-formed
541 // program our base object expression is "this".
542 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
543 if (!MD->isStatic()) {
544 QualType AnonFieldType
545 = Context.getTagDeclType(
546 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
547 QualType ThisType = Context.getTagDeclType(MD->getParent());
548 if ((Context.getCanonicalType(AnonFieldType)
549 == Context.getCanonicalType(ThisType)) ||
550 IsDerivedFrom(ThisType, AnonFieldType)) {
551 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000552 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000553 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000554 BaseObjectIsPointer = true;
555 }
556 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000557 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
558 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000559 }
560 ExtraQuals = MD->getTypeQualifiers();
561 }
562
563 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000564 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
565 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000566 }
567
568 // Build the implicit member references to the field of the
569 // anonymous struct/union.
570 Expr *Result = BaseObjectExpr;
571 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
572 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
573 FI != FIEnd; ++FI) {
574 QualType MemberType = (*FI)->getType();
575 if (!(*FI)->isMutable()) {
576 unsigned combinedQualifiers
577 = MemberType.getCVRQualifiers() | ExtraQuals;
578 MemberType = MemberType.getQualifiedType(combinedQualifiers);
579 }
Steve Naroff6ece14c2009-01-21 00:14:39 +0000580 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
581 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000582 BaseObjectIsPointer = false;
583 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000584 }
585
Sebastian Redlcd965b92009-01-18 18:53:16 +0000586 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000587}
588
Douglas Gregor10c42622008-11-18 15:03:34 +0000589/// ActOnDeclarationNameExpr - The parser has read some kind of name
590/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
591/// performs lookup on that name and returns an expression that refers
592/// to that name. This routine isn't directly called from the parser,
593/// because the parser doesn't know about DeclarationName. Rather,
594/// this routine is called by ActOnIdentifierExpr,
595/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
596/// which form the DeclarationName from the corresponding syntactic
597/// forms.
598///
599/// HasTrailingLParen indicates whether this identifier is used in a
600/// function call context. LookupCtx is only used for a C++
601/// qualified-id (foo::bar) to indicate the class or namespace that
602/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000603///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000604/// isAddressOfOperand means that this expression is the direct operand
605/// of an address-of operator. This matters because this is the only
606/// situation where a qualified name referencing a non-static member may
607/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000608Sema::OwningExprResult
609Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
610 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +0000611 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000612 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000613 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000614 if (SS && SS->isInvalid())
615 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000616
617 // C++ [temp.dep.expr]p3:
618 // An id-expression is type-dependent if it contains:
619 // -- a nested-name-specifier that contains a class-name that
620 // names a dependent type.
621 if (SS && isDependentScopeSpecifier(*SS)) {
622 llvm::SmallVector<NestedNameSpecifier, 16> Specs;
623 for (CXXScopeSpec::iterator Spec = SS->begin(), SpecEnd = SS->end();
624 Spec != SpecEnd; ++Spec)
625 Specs.push_back(NestedNameSpecifier::getFromOpaquePtr(*Spec));
626 return Owned(UnresolvedDeclRefExpr::Create(Context, Name, Loc,
627 SS->getRange(), &Specs[0],
628 Specs.size()));
629 }
630
Douglas Gregor3e41d602009-02-13 23:20:09 +0000631 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
632 false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000633
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000634 NamedDecl *D = 0;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000635 if (Lookup.isAmbiguous()) {
636 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
637 SS && SS->isSet() ? SS->getRange()
638 : SourceRange());
639 return ExprError();
640 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000641 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000642
Chris Lattner8a934232008-03-31 00:36:02 +0000643 // If this reference is in an Objective-C method, then ivar lookup happens as
644 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000645 IdentifierInfo *II = Name.getAsIdentifierInfo();
646 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000647 // There are two cases to handle here. 1) scoped lookup could have failed,
648 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000649 // found a decl, but that decl is outside the current instance method (i.e.
650 // a global variable). In these two cases, we do a lookup for an ivar with
651 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000652 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000653 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000654 ObjCInterfaceDecl *ClassDeclared;
655 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000656 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000657 if (DiagnoseUseOfDecl(IV, Loc))
658 return ExprError();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000659 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
660 // If a class method attemps to use a free standing ivar, this is
661 // an error.
662 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
663 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
664 << IV->getDeclName());
665 // If a class method uses a global variable, even if an ivar with
666 // same name exists, use the global.
667 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000668 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
669 ClassDeclared != IFace)
670 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000671 // FIXME: This should use a new expr for a direct reference, don't turn
672 // this into Self->ivar, just return a BareIVarExpr or something.
673 IdentifierInfo &II = Context.Idents.get("self");
674 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
675 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
676 Loc, static_cast<Expr*>(SelfExpr.release()),
677 true, true);
678 Context.setFieldDecl(IFace, IV, MRef);
679 return Owned(MRef);
680 }
Chris Lattner8a934232008-03-31 00:36:02 +0000681 }
682 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000683 else if (getCurMethodDecl()->isInstanceMethod()) {
684 // We should warn if a local variable hides an ivar.
685 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000686 ObjCInterfaceDecl *ClassDeclared;
687 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
688 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
689 IFace == ClassDeclared)
690 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
691 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000692 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000693 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000694 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000695 QualType T;
696
697 if (getCurMethodDecl()->isInstanceMethod())
698 T = Context.getPointerType(Context.getObjCInterfaceType(
699 getCurMethodDecl()->getClassInterface()));
700 else
701 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000702 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000703 }
Chris Lattner8a934232008-03-31 00:36:02 +0000704 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000705
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000706 // Determine whether this name might be a candidate for
707 // argument-dependent lookup.
708 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
709 HasTrailingLParen;
710
711 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000712 // We've seen something of the form
713 //
714 // identifier(
715 //
716 // and we did not find any entity by the name
717 // "identifier". However, this identifier is still subject to
718 // argument-dependent lookup, so keep track of the name.
719 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
720 Context.OverloadTy,
721 Loc));
722 }
723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 if (D == 0) {
725 // Otherwise, this could be an implicitly declared function reference (legal
726 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000727 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000728 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000729 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 else {
731 // If this name wasn't predeclared and if this is not a function call,
732 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000733 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000734 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
735 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000736 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
737 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000738 return ExprError(Diag(Loc, diag::err_undeclared_use)
739 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000740 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000741 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 }
743 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000744
Sebastian Redlebc07d52009-02-03 20:19:35 +0000745 // If this is an expression of the form &Class::member, don't build an
746 // implicit member ref, because we want a pointer to the member in general,
747 // not any specific instance's member.
748 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000749 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000750 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000751 QualType DType;
752 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
753 DType = FD->getType().getNonReferenceType();
754 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
755 DType = Method->getType();
756 } else if (isa<OverloadedFunctionDecl>(D)) {
757 DType = Context.OverloadTy;
758 }
759 // Could be an inner type. That's diagnosed below, so ignore it here.
760 if (!DType.isNull()) {
761 // The pointer is type- and value-dependent if it points into something
762 // dependent.
763 bool Dependent = false;
764 for (; DC; DC = DC->getParent()) {
765 // FIXME: could stop early at namespace scope.
766 if (DC->isRecord()) {
767 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
768 if (Context.getTypeDeclType(Record)->isDependentType()) {
769 Dependent = true;
770 break;
771 }
772 }
773 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000774 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redlebc07d52009-02-03 20:19:35 +0000775 }
776 }
777 }
778
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000779 // We may have found a field within an anonymous union or struct
780 // (C++ [class.union]).
781 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
782 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
783 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000784
Douglas Gregor88a35142008-12-22 05:46:06 +0000785 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
786 if (!MD->isStatic()) {
787 // C++ [class.mfct.nonstatic]p2:
788 // [...] if name lookup (3.4.1) resolves the name in the
789 // id-expression to a nonstatic nontype member of class X or of
790 // a base class of X, the id-expression is transformed into a
791 // class member access expression (5.2.5) using (*this) (9.3.2)
792 // as the postfix-expression to the left of the '.' operator.
793 DeclContext *Ctx = 0;
794 QualType MemberType;
795 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
796 Ctx = FD->getDeclContext();
797 MemberType = FD->getType();
798
799 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
800 MemberType = RefType->getPointeeType();
801 else if (!FD->isMutable()) {
802 unsigned combinedQualifiers
803 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
804 MemberType = MemberType.getQualifiedType(combinedQualifiers);
805 }
806 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
807 if (!Method->isStatic()) {
808 Ctx = Method->getParent();
809 MemberType = Method->getType();
810 }
811 } else if (OverloadedFunctionDecl *Ovl
812 = dyn_cast<OverloadedFunctionDecl>(D)) {
813 for (OverloadedFunctionDecl::function_iterator
814 Func = Ovl->function_begin(),
815 FuncEnd = Ovl->function_end();
816 Func != FuncEnd; ++Func) {
817 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
818 if (!DMethod->isStatic()) {
819 Ctx = Ovl->getDeclContext();
820 MemberType = Context.OverloadTy;
821 break;
822 }
823 }
824 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000825
826 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000827 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
828 QualType ThisType = Context.getTagDeclType(MD->getParent());
829 if ((Context.getCanonicalType(CtxType)
830 == Context.getCanonicalType(ThisType)) ||
831 IsDerivedFrom(ThisType, CtxType)) {
832 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000833 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000834 MD->getThisType(Context));
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000835 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stumpeed9cac2009-02-19 03:04:26 +0000836 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000837 }
838 }
839 }
840 }
841
Douglas Gregor44b43212008-12-11 16:49:14 +0000842 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000843 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
844 if (MD->isStatic())
845 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000846 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
847 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000848 }
849
Douglas Gregor88a35142008-12-22 05:46:06 +0000850 // Any other ways we could have found the field in a well-formed
851 // program would have been turned into implicit member expressions
852 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000853 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
854 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000855 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000856
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000858 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000859 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000860 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000861 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000862 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863
Steve Naroffdd972f22008-09-05 22:11:13 +0000864 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000865 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000866 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
867 false, false, SS));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000868 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
869 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
870 false, false, SS));
Steve Naroffdd972f22008-09-05 22:11:13 +0000871 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000872
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000873 // Check whether this declaration can be used. Note that we suppress
874 // this check when we're going to perform argument-dependent lookup
875 // on this function name, because this might not be the function
876 // that overload resolution actually selects.
877 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
878 return ExprError();
879
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000880 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000881 // Warn about constructs like:
882 // if (void *X = foo()) { ... } else { X }.
883 // In the else block, the pointer is always false.
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000884 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
885 Scope *CheckS = S;
886 while (CheckS) {
887 if (CheckS->isWithinElse() &&
888 CheckS->getControlParent()->isDeclScope(Var)) {
889 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000890 ExprError(Diag(Loc, diag::warn_value_always_false)
891 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000892 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000893 ExprError(Diag(Loc, diag::warn_value_always_zero)
894 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000895 break;
896 }
897
898 // Move up one more control parent to check again.
899 CheckS = CheckS->getControlParent();
900 if (CheckS)
901 CheckS = CheckS->getParent();
902 }
903 }
Douglas Gregor2224f842009-02-25 16:33:18 +0000904 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
905 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
906 // C99 DR 316 says that, if a function type comes from a
907 // function definition (without a prototype), that type is only
908 // used for checking compatibility. Therefore, when referencing
909 // the function, we pretend that we don't have the full function
910 // type.
911 QualType T = Func->getType();
912 QualType NoProtoType = T;
Douglas Gregor72564e72009-02-26 23:50:07 +0000913 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
914 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor2224f842009-02-25 16:33:18 +0000915 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
916 }
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000917 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000918
919 // Only create DeclRefExpr's for valid Decl's.
920 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000921 return ExprError();
922
Chris Lattner639e2d32008-10-20 05:16:36 +0000923 // If the identifier reference is inside a block, and it refers to a value
924 // that is outside the block, create a BlockDeclRefExpr instead of a
925 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
926 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000927 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000928 // We do not do this for things like enum constants, global variables, etc,
929 // as they do not get snapshotted.
930 //
931 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000932 // Blocks that have these can't be constant.
933 CurBlock->hasBlockDeclRefExprs = true;
934
Steve Naroff090276f2008-10-10 01:28:17 +0000935 // The BlocksAttr indicates the variable is bound by-reference.
936 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000937 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000938 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000939
Steve Naroff090276f2008-10-10 01:28:17 +0000940 // Variable will be bound by-copy, make it const within the closure.
941 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000942 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000943 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000944 }
945 // If this reference is not in a block or if the referenced variable is
946 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000947
Douglas Gregor898574e2008-12-05 23:32:09 +0000948 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000949 bool ValueDependent = false;
950 if (getLangOptions().CPlusPlus) {
951 // C++ [temp.dep.expr]p3:
952 // An id-expression is type-dependent if it contains:
953 // - an identifier that was declared with a dependent type,
954 if (VD->getType()->isDependentType())
955 TypeDependent = true;
956 // - FIXME: a template-id that is dependent,
957 // - a conversion-function-id that specifies a dependent type,
958 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
959 Name.getCXXNameType()->isDependentType())
960 TypeDependent = true;
961 // - a nested-name-specifier that contains a class-name that
962 // names a dependent type.
963 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000964 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +0000965 DC; DC = DC->getParent()) {
966 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000967 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000968 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
969 if (Context.getTypeDeclType(Record)->isDependentType()) {
970 TypeDependent = true;
971 break;
972 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000973 }
974 }
975 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000976
Douglas Gregor83f96f62008-12-10 20:57:37 +0000977 // C++ [temp.dep.constexpr]p2:
978 //
979 // An identifier is value-dependent if it is:
980 // - a name declared with a dependent type,
981 if (TypeDependent)
982 ValueDependent = true;
983 // - the name of a non-type template parameter,
984 else if (isa<NonTypeTemplateParmDecl>(VD))
985 ValueDependent = true;
986 // - a constant with integral or enumeration type and is
987 // initialized with an expression that is value-dependent
988 // (FIXME!).
989 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000990
Sebastian Redlcd965b92009-01-18 18:53:16 +0000991 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
992 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000993}
994
Sebastian Redlcd965b92009-01-18 18:53:16 +0000995Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
996 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000997 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000998
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001000 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001001 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1002 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1003 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001005
Chris Lattnerfa28b302008-01-12 08:14:25 +00001006 // Pre-defined identifiers are of type char[x], where x is the length of the
1007 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +00001008 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +00001009 if (FunctionDecl *FD = getCurFunctionDecl())
1010 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001011 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1012 Length = MD->getSynthesizedMethodSize();
1013 else {
1014 Diag(Loc, diag::ext_predef_outside_function);
1015 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1016 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1017 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001018
1019
Chris Lattner8f978d52008-01-12 19:32:28 +00001020 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +00001021 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +00001022 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +00001023 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001024}
1025
Sebastian Redlcd965b92009-01-18 18:53:16 +00001026Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 llvm::SmallString<16> CharBuffer;
1028 CharBuffer.resize(Tok.getLength());
1029 const char *ThisTokBegin = &CharBuffer[0];
1030 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001031
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1033 Tok.getLocation(), PP);
1034 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001035 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001036
1037 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1038
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001039 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1040 Literal.isWide(),
1041 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001042}
1043
Sebastian Redlcd965b92009-01-18 18:53:16 +00001044Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1045 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001046 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1047 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001048 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001049 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001050 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001051 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 }
Ted Kremenek28396602009-01-13 23:19:12 +00001053
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001055 // Add padding so that NumericLiteralParser can overread by one character.
1056 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001058
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 // Get the spelling of the token, which eliminates trigraphs, etc.
1060 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001061
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1063 Tok.getLocation(), PP);
1064 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001065 return ExprError();
1066
Chris Lattner5d661452007-08-26 03:42:43 +00001067 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001068
Chris Lattner5d661452007-08-26 03:42:43 +00001069 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001070 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001071 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001072 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001073 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001074 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001075 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001076 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001077
1078 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1079
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001080 // isExact will be set by GetFloatValue().
1081 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001082 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1083 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001084
Chris Lattner5d661452007-08-26 03:42:43 +00001085 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001086 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001087 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001088 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001089
Neil Boothb9449512007-08-29 22:00:19 +00001090 // long long is a C99 feature.
1091 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001092 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001093 Diag(Tok.getLocation(), diag::ext_longlong);
1094
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001096 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001097
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 if (Literal.GetIntegerValue(ResultVal)) {
1099 // If this value didn't fit into uintmax_t, warn and force to ull.
1100 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001101 Ty = Context.UnsignedLongLongTy;
1102 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001103 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 } else {
1105 // If this value fits into a ULL, try to figure out what else it fits into
1106 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001107
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1109 // be an unsigned int.
1110 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1111
1112 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001113 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001114 if (!Literal.isLong && !Literal.isLongLong) {
1115 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001116 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001117
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 // Does it fit in a unsigned int?
1119 if (ResultVal.isIntN(IntSize)) {
1120 // Does it fit in a signed int?
1121 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001122 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001124 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001125 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001130 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001131 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001132
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 // Does it fit in a unsigned long?
1134 if (ResultVal.isIntN(LongSize)) {
1135 // Does it fit in a signed long?
1136 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001137 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001139 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001140 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001142 }
1143
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001145 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001146 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001147
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 // Does it fit in a unsigned long long?
1149 if (ResultVal.isIntN(LongLongSize)) {
1150 // Does it fit in a signed long long?
1151 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001152 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001154 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001155 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 }
1157 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001158
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 // If we still couldn't decide a type, we probably have something that
1160 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001161 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001163 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001164 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001166
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001167 if (ResultVal.getBitWidth() != Width)
1168 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001170 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001172
Chris Lattner5d661452007-08-26 03:42:43 +00001173 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1174 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001175 Res = new (Context) ImaginaryLiteral(Res,
1176 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001177
1178 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001179}
1180
Sebastian Redlcd965b92009-01-18 18:53:16 +00001181Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1182 SourceLocation R, ExprArg Val) {
1183 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001184 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001185 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001186}
1187
1188/// The UsualUnaryConversions() function is *not* called by this routine.
1189/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001190bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001191 SourceLocation OpLoc,
1192 const SourceRange &ExprRange,
1193 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001194 if (exprType->isDependentType())
1195 return false;
1196
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001198 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001200 if (isSizeof)
1201 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1202 return false;
1203 }
1204
1205 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001206 Diag(OpLoc, diag::ext_sizeof_void_type)
1207 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001208 return false;
1209 }
Sebastian Redl05189992008-11-11 17:56:53 +00001210
Douglas Gregor86447ec2009-03-09 16:13:40 +00001211 return RequireCompleteType(OpLoc, exprType,
Chris Lattner01072922009-01-24 19:46:37 +00001212 isSizeof ? diag::err_sizeof_incomplete_type :
1213 diag::err_alignof_incomplete_type,
1214 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001215}
1216
Chris Lattner31e21e02009-01-24 20:17:12 +00001217bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1218 const SourceRange &ExprRange) {
1219 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001220
Chris Lattner31e21e02009-01-24 20:17:12 +00001221 // alignof decl is always ok.
1222 if (isa<DeclRefExpr>(E))
1223 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001224
1225 // Cannot know anything else if the expression is dependent.
1226 if (E->isTypeDependent())
1227 return false;
1228
Chris Lattner31e21e02009-01-24 20:17:12 +00001229 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1230 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1231 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001232 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001233 return true;
1234 }
1235 // Other fields are ok.
1236 return false;
1237 }
1238 }
1239 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1240}
1241
Douglas Gregorba498172009-03-13 21:01:28 +00001242/// \brief Build a sizeof or alignof expression given a type operand.
1243Action::OwningExprResult
1244Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1245 bool isSizeOf, SourceRange R) {
1246 if (T.isNull())
1247 return ExprError();
1248
1249 if (!T->isDependentType() &&
1250 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1251 return ExprError();
1252
1253 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1254 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1255 Context.getSizeType(), OpLoc,
1256 R.getEnd()));
1257}
1258
1259/// \brief Build a sizeof or alignof expression given an expression
1260/// operand.
1261Action::OwningExprResult
1262Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1263 bool isSizeOf, SourceRange R) {
1264 // Verify that the operand is valid.
1265 bool isInvalid = false;
1266 if (E->isTypeDependent()) {
1267 // Delay type-checking for type-dependent expressions.
1268 } else if (!isSizeOf) {
1269 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1270 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1271 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1272 isInvalid = true;
1273 } else {
1274 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1275 }
1276
1277 if (isInvalid)
1278 return ExprError();
1279
1280 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1281 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1282 Context.getSizeType(), OpLoc,
1283 R.getEnd()));
1284}
1285
Sebastian Redl05189992008-11-11 17:56:53 +00001286/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1287/// the same for @c alignof and @c __alignof
1288/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001289Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001290Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1291 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001293 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001294
Sebastian Redl05189992008-11-11 17:56:53 +00001295 if (isType) {
Douglas Gregorba498172009-03-13 21:01:28 +00001296 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1297 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1298 }
Sebastian Redl05189992008-11-11 17:56:53 +00001299
Douglas Gregorba498172009-03-13 21:01:28 +00001300 // Get the end location.
1301 Expr *ArgEx = (Expr *)TyOrEx;
1302 Action::OwningExprResult Result
1303 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1304
1305 if (Result.isInvalid())
1306 DeleteExpr(ArgEx);
1307
1308 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309}
1310
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001311QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001312 if (V->isTypeDependent())
1313 return Context.DependentTy;
1314
Chris Lattnerdbb36972007-08-24 21:16:53 +00001315 DefaultFunctionArrayConversion(V);
1316
Chris Lattnercc26ed72007-08-26 05:39:26 +00001317 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001318 if (const ComplexType *CT = V->getType()->getAsComplexType())
1319 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001320
1321 // Otherwise they pass through real integer and floating point types here.
1322 if (V->getType()->isArithmeticType())
1323 return V->getType();
1324
1325 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001326 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1327 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001328 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001329}
1330
1331
Reid Spencer5f016e22007-07-11 17:01:13 +00001332
Sebastian Redl0eb23302009-01-19 00:08:26 +00001333Action::OwningExprResult
1334Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1335 tok::TokenKind Kind, ExprArg Input) {
1336 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 UnaryOperator::Opcode Opc;
1339 switch (Kind) {
1340 default: assert(0 && "Unknown unary op!");
1341 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1342 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1343 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001344
Douglas Gregor74253732008-11-19 15:42:04 +00001345 if (getLangOptions().CPlusPlus &&
1346 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1347 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001348 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001349 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1350
1351 // C++ [over.inc]p1:
1352 //
1353 // [...] If the function is a member function with one
1354 // parameter (which shall be of type int) or a non-member
1355 // function with two parameters (the second of which shall be
1356 // of type int), it defines the postfix increment operator ++
1357 // for objects of that type. When the postfix increment is
1358 // called as a result of using the ++ operator, the int
1359 // argument will have value zero.
1360 Expr *Args[2] = {
1361 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001362 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1363 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001364 };
1365
1366 // Build the candidate set for overloading
1367 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001368 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001369
1370 // Perform overload resolution.
1371 OverloadCandidateSet::iterator Best;
1372 switch (BestViableFunction(CandidateSet, Best)) {
1373 case OR_Success: {
1374 // We found a built-in operator or an overloaded operator.
1375 FunctionDecl *FnDecl = Best->Function;
1376
1377 if (FnDecl) {
1378 // We matched an overloaded operator. Build a call to that
1379 // operator.
1380
1381 // Convert the arguments.
1382 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1383 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001384 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001385 } else {
1386 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001387 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001388 FnDecl->getParamDecl(0)->getType(),
1389 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001390 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001391 }
1392
1393 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001394 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001395 = FnDecl->getType()->getAsFunctionType()->getResultType();
1396 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001397
Douglas Gregor74253732008-11-19 15:42:04 +00001398 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001399 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001400 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001401 UsualUnaryConversions(FnExpr);
1402
Sebastian Redl0eb23302009-01-19 00:08:26 +00001403 Input.release();
Douglas Gregor063daf62009-03-13 18:40:31 +00001404 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1405 Args, 2, ResultTy,
1406 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001407 } else {
1408 // We matched a built-in operator. Convert the arguments, then
1409 // break out so that we will build the appropriate built-in
1410 // operator node.
1411 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1412 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001413 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001414
1415 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001416 }
Douglas Gregor74253732008-11-19 15:42:04 +00001417 }
1418
1419 case OR_No_Viable_Function:
1420 // No viable function; fall through to handling this as a
1421 // built-in operator, which will produce an error message for us.
1422 break;
1423
1424 case OR_Ambiguous:
1425 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1426 << UnaryOperator::getOpcodeStr(Opc)
1427 << Arg->getSourceRange();
1428 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001429 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001430
1431 case OR_Deleted:
1432 Diag(OpLoc, diag::err_ovl_deleted_oper)
1433 << Best->Function->isDeleted()
1434 << UnaryOperator::getOpcodeStr(Opc)
1435 << Arg->getSourceRange();
1436 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1437 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001438 }
1439
1440 // Either we found no viable overloaded operator or we matched a
1441 // built-in operator. In either case, fall through to trying to
1442 // build a built-in operation.
1443 }
1444
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001445 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1446 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001448 return ExprError();
1449 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001450 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001451}
1452
Sebastian Redl0eb23302009-01-19 00:08:26 +00001453Action::OwningExprResult
1454Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1455 ExprArg Idx, SourceLocation RLoc) {
1456 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1457 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001458
Douglas Gregor337c6b92008-11-19 17:17:41 +00001459 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001460 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001461 LHSExp->getType()->isEnumeralType() ||
1462 RHSExp->getType()->isRecordType() ||
1463 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001464 // Add the appropriate overloaded operators (C++ [over.match.oper])
1465 // to the candidate set.
1466 OverloadCandidateSet CandidateSet;
1467 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor063daf62009-03-13 18:40:31 +00001468 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1469 SourceRange(LLoc, RLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001470
Douglas Gregor337c6b92008-11-19 17:17:41 +00001471 // Perform overload resolution.
1472 OverloadCandidateSet::iterator Best;
1473 switch (BestViableFunction(CandidateSet, Best)) {
1474 case OR_Success: {
1475 // We found a built-in operator or an overloaded operator.
1476 FunctionDecl *FnDecl = Best->Function;
1477
1478 if (FnDecl) {
1479 // We matched an overloaded operator. Build a call to that
1480 // operator.
1481
1482 // Convert the arguments.
1483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1484 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1485 PerformCopyInitialization(RHSExp,
1486 FnDecl->getParamDecl(0)->getType(),
1487 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001488 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001489 } else {
1490 // Convert the arguments.
1491 if (PerformCopyInitialization(LHSExp,
1492 FnDecl->getParamDecl(0)->getType(),
1493 "passing") ||
1494 PerformCopyInitialization(RHSExp,
1495 FnDecl->getParamDecl(1)->getType(),
1496 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001497 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001498 }
1499
1500 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001501 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001502 = FnDecl->getType()->getAsFunctionType()->getResultType();
1503 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001504
Douglas Gregor337c6b92008-11-19 17:17:41 +00001505 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001506 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1507 SourceLocation());
Douglas Gregor337c6b92008-11-19 17:17:41 +00001508 UsualUnaryConversions(FnExpr);
1509
Sebastian Redl0eb23302009-01-19 00:08:26 +00001510 Base.release();
1511 Idx.release();
Douglas Gregor063daf62009-03-13 18:40:31 +00001512 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1513 FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001514 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001515 } else {
1516 // We matched a built-in operator. Convert the arguments, then
1517 // break out so that we will build the appropriate built-in
1518 // operator node.
1519 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1520 "passing") ||
1521 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1522 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001523 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001524
1525 break;
1526 }
1527 }
1528
1529 case OR_No_Viable_Function:
1530 // No viable function; fall through to handling this as a
1531 // built-in operator, which will produce an error message for us.
1532 break;
1533
1534 case OR_Ambiguous:
1535 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1536 << "[]"
1537 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1538 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001539 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001540
1541 case OR_Deleted:
1542 Diag(LLoc, diag::err_ovl_deleted_oper)
1543 << Best->Function->isDeleted()
1544 << "[]"
1545 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1546 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1547 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001548 }
1549
1550 // Either we found no viable overloaded operator or we matched a
1551 // built-in operator. In either case, fall through to trying to
1552 // build a built-in operation.
1553 }
1554
Chris Lattner12d9ff62007-07-16 00:14:47 +00001555 // Perform default conversions.
1556 DefaultFunctionArrayConversion(LHSExp);
1557 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001558
Chris Lattner12d9ff62007-07-16 00:14:47 +00001559 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001560
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001562 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001563 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001565 Expr *BaseExpr, *IndexExpr;
1566 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001567 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1568 BaseExpr = LHSExp;
1569 IndexExpr = RHSExp;
1570 ResultType = Context.DependentTy;
1571 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001572 BaseExpr = LHSExp;
1573 IndexExpr = RHSExp;
1574 // FIXME: need to deal with const...
1575 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001576 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001577 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001578 BaseExpr = RHSExp;
1579 IndexExpr = LHSExp;
1580 // FIXME: need to deal with const...
1581 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001582 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1583 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001584 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001585
Chris Lattner12d9ff62007-07-16 00:14:47 +00001586 // FIXME: need to deal with const...
1587 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001589 return ExprError(Diag(LHSExp->getLocStart(),
1590 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1591 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 // C99 6.5.2.1p1
Sebastian Redl28507842009-02-26 14:39:58 +00001593 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001594 return ExprError(Diag(IndexExpr->getLocStart(),
1595 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001596
Chris Lattner12d9ff62007-07-16 00:14:47 +00001597 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1598 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001599 // void (*)(int)) and pointers to incomplete types. Functions are not
1600 // objects in C99.
Sebastian Redl28507842009-02-26 14:39:58 +00001601 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001602 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001603 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001604 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001605
Sebastian Redl0eb23302009-01-19 00:08:26 +00001606 Base.release();
1607 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001608 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001609 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001610}
1611
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001612QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001613CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001614 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001615 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001616
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001617 // The vector accessor can't exceed the number of elements.
1618 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001619
Mike Stumpeed9cac2009-02-19 03:04:26 +00001620 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001621 // special names that indicate a subset of exactly half the elements are
1622 // to be selected.
1623 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001624
Nate Begeman353417a2009-01-18 01:47:54 +00001625 // This flag determines whether or not CompName has an 's' char prefix,
1626 // indicating that it is a string of hex values to be used as vector indices.
1627 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001628
1629 // Check that we've found one of the special components, or that the component
1630 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001631 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001632 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1633 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001634 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001635 do
1636 compStr++;
1637 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001638 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001639 do
1640 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001641 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001642 }
Nate Begeman353417a2009-01-18 01:47:54 +00001643
Mike Stumpeed9cac2009-02-19 03:04:26 +00001644 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001645 // We didn't get to the end of the string. This means the component names
1646 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001647 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1648 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001649 return QualType();
1650 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001651
Nate Begeman353417a2009-01-18 01:47:54 +00001652 // Ensure no component accessor exceeds the width of the vector type it
1653 // operates on.
1654 if (!HalvingSwizzle) {
1655 compStr = CompName.getName();
1656
1657 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001658 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001659
1660 while (*compStr) {
1661 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1662 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1663 << baseType << SourceRange(CompLoc);
1664 return QualType();
1665 }
1666 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001667 }
Nate Begeman8a997642008-05-09 06:41:27 +00001668
Nate Begeman353417a2009-01-18 01:47:54 +00001669 // If this is a halving swizzle, verify that the base type has an even
1670 // number of elements.
1671 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001672 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001673 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001674 return QualType();
1675 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001676
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001677 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001678 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001679 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001680 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001681 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001682 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1683 : CompName.getLength();
1684 if (HexSwizzle)
1685 CompSize--;
1686
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001687 if (CompSize == 1)
1688 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001689
Nate Begeman213541a2008-04-18 23:10:10 +00001690 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001691 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001692 // diagostics look bad. We want extended vector types to appear built-in.
1693 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1694 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1695 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001696 }
1697 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001698}
1699
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001700static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1701 IdentifierInfo &Member,
1702 const Selector &Sel) {
1703
1704 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
1705 return PD;
1706 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1707 return OMD;
1708
1709 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1710 E = PDecl->protocol_end(); I != E; ++I) {
1711 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel))
1712 return D;
1713 }
1714 return 0;
1715}
1716
1717static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1718 IdentifierInfo &Member,
1719 const Selector &Sel) {
1720 // Check protocols on qualified interfaces.
1721 Decl *GDecl = 0;
1722 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1723 E = QIdTy->qual_end(); I != E; ++I) {
1724 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1725 GDecl = PD;
1726 break;
1727 }
1728 // Also must look for a getter name which uses property syntax.
1729 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1730 GDecl = OMD;
1731 break;
1732 }
1733 }
1734 if (!GDecl) {
1735 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1736 E = QIdTy->qual_end(); I != E; ++I) {
1737 // Search in the protocol-qualifier list of current protocol.
1738 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel);
1739 if (GDecl)
1740 return GDecl;
1741 }
1742 }
1743 return GDecl;
1744}
Chris Lattner76a642f2009-02-15 22:43:40 +00001745
Sebastian Redl0eb23302009-01-19 00:08:26 +00001746Action::OwningExprResult
1747Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1748 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001749 IdentifierInfo &Member,
1750 DeclTy *ObjCImpDecl) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001751 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001752 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001753
1754 // Perform default conversions.
1755 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001756
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001757 QualType BaseType = BaseExpr->getType();
1758 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001759
Chris Lattner68a057b2008-07-21 04:36:39 +00001760 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1761 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001763 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001764 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001765 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001766 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1767 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001768 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001769 return ExprError(Diag(MemberLoc,
1770 diag::err_typecheck_member_reference_arrow)
1771 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001773
Chris Lattner68a057b2008-07-21 04:36:39 +00001774 // Handle field access to simple records. This also handles access to fields
1775 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001776 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001777 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00001778 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001779 diag::err_typecheck_incomplete_tag,
1780 BaseExpr->getSourceRange()))
1781 return ExprError();
1782
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001783 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001784 // FIXME: Qualified name lookup for C++ is a bit more complicated
1785 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001786 LookupResult Result
Mike Stumpeed9cac2009-02-19 03:04:26 +00001787 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001788 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001789
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001790 NamedDecl *MemberDecl = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001791 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001792 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1793 << &Member << BaseExpr->getSourceRange());
1794 else if (Result.isAmbiguous()) {
1795 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1796 MemberLoc, BaseExpr->getSourceRange());
1797 return ExprError();
1798 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001799 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001800
Chris Lattner56cd21b2009-02-13 22:08:30 +00001801 // If the decl being referenced had an error, return an error for this
1802 // sub-expr without emitting another error, in order to avoid cascading
1803 // error cases.
1804 if (MemberDecl->isInvalidDecl())
1805 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001806
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001807 // Check the use of this field
1808 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1809 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00001810
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001811 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001812 // We may have found a field within an anonymous union or struct
1813 // (C++ [class.union]).
1814 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001815 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001816 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001817
Douglas Gregor86f19402008-12-20 23:49:58 +00001818 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1819 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001820 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001821 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1822 MemberType = Ref->getPointeeType();
1823 else {
1824 unsigned combinedQualifiers =
1825 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001826 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001827 combinedQualifiers &= ~QualType::Const;
1828 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1829 }
Eli Friedman51019072008-02-06 22:48:16 +00001830
Steve Naroff6ece14c2009-01-21 00:14:39 +00001831 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1832 MemberLoc, MemberType));
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001833 } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001834 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001835 Var, MemberLoc,
1836 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001837 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001838 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001839 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001840 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001841 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001842 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001843 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001844 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001845 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1846 Enum, MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001847 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001848 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1849 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001850
Douglas Gregor86f19402008-12-20 23:49:58 +00001851 // We found a declaration kind that we didn't expect. This is a
1852 // generic error message that tells the user that she can't refer
1853 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001854 return ExprError(Diag(MemberLoc,
1855 diag::err_typecheck_member_reference_unknown)
1856 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001857 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001858
Chris Lattnera38e6b12008-07-21 04:59:05 +00001859 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1860 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001861 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001862 ObjCInterfaceDecl *ClassDeclared;
1863 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1864 ClassDeclared)) {
Chris Lattner56cd21b2009-02-13 22:08:30 +00001865 // If the decl being referenced had an error, return an error for this
1866 // sub-expr without emitting another error, in order to avoid cascading
1867 // error cases.
1868 if (IV->isInvalidDecl())
1869 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001870
1871 // Check whether we can reference this field.
1872 if (DiagnoseUseOfDecl(IV, MemberLoc))
1873 return ExprError();
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001874 if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1875 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1876 if (ObjCMethodDecl *MD = getCurMethodDecl())
1877 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001878 else if (ObjCImpDecl && getCurFunctionDecl()) {
1879 // Case of a c-function declared inside an objc implementation.
1880 // FIXME: For a c-style function nested inside an objc implementation
1881 // class, there is no implementation context available, so we pass down
1882 // the context as argument to this routine. Ideally, this context need
1883 // be passed down in the AST node and somehow calculated from the AST
1884 // for a function decl.
1885 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1886 if (ObjCImplementationDecl *IMPD =
1887 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1888 ClassOfMethodDecl = IMPD->getClassInterface();
1889 else if (ObjCCategoryImplDecl* CatImplClass =
1890 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1891 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Naroffb06d8752009-03-04 18:34:24 +00001892 }
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001893 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001894 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001895 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001896 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1897 }
1898 // @protected
1899 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1900 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1901 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001902
1903 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff6ece14c2009-01-21 00:14:39 +00001904 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001905 OpKind == tok::arrow);
1906 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001907 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001908 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001909 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1910 << IFTy->getDecl()->getDeclName() << &Member
1911 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001912 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001913
Chris Lattnera38e6b12008-07-21 04:59:05 +00001914 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1915 // pointer to a (potentially qualified) interface type.
1916 const PointerType *PTy;
1917 const ObjCInterfaceType *IFTy;
1918 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1919 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1920 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001921
Daniel Dunbar2307d312008-09-03 01:05:41 +00001922 // Search for a declared property first.
Chris Lattner7eba82e2009-02-16 18:35:08 +00001923 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001924 // Check whether we can reference this property.
1925 if (DiagnoseUseOfDecl(PD, MemberLoc))
1926 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001927
Steve Naroff6ece14c2009-01-21 00:14:39 +00001928 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001929 MemberLoc, BaseExpr));
1930 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001931
Daniel Dunbar2307d312008-09-03 01:05:41 +00001932 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001933 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1934 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner7eba82e2009-02-16 18:35:08 +00001935 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001936 // Check whether we can reference this property.
1937 if (DiagnoseUseOfDecl(PD, MemberLoc))
1938 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001939
Steve Naroff6ece14c2009-01-21 00:14:39 +00001940 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001941 MemberLoc, BaseExpr));
1942 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001943
1944 // If that failed, look for an "implicit" property by seeing if the nullary
1945 // selector is implemented.
1946
1947 // FIXME: The logic for looking up nullary and unary selectors should be
1948 // shared with the code in ActOnInstanceMessage.
1949
1950 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1951 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001952
Daniel Dunbar2307d312008-09-03 01:05:41 +00001953 // If this reference is in an @implementation, check for 'private' methods.
1954 if (!Getter)
Steve Narofff1787282009-03-11 15:15:01 +00001955 if (ObjCImplementationDecl *ImpDecl =
1956 ObjCImplementations[IFace->getIdentifier()])
1957 Getter = ImpDecl->getInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001958
Steve Naroff7692ed62008-10-22 19:16:27 +00001959 // Look through local category implementations associated with the class.
1960 if (!Getter) {
1961 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1962 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1963 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1964 }
1965 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001966 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001967 // Check if we can reference this property.
1968 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1969 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00001970 }
1971 // If we found a getter then this may be a valid dot-reference, we
1972 // will look for the matching setter, in case it is needed.
1973 Selector SetterSel =
1974 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1975 PP.getSelectorTable(), &Member);
1976 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1977 if (!Setter) {
1978 // If this reference is in an @implementation, also check for 'private'
1979 // methods.
Steve Narofff1787282009-03-11 15:15:01 +00001980 if (ObjCImplementationDecl *ImpDecl =
1981 ObjCImplementations[IFace->getIdentifier()])
1982 Setter = ImpDecl->getInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00001983 }
1984 // Look through local category implementations associated with the class.
1985 if (!Setter) {
1986 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1987 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1988 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001989 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001990 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001991
Steve Naroff1ca66942009-03-11 13:48:17 +00001992 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1993 return ExprError();
1994
1995 if (Getter || Setter) {
1996 QualType PType;
1997
1998 if (Getter)
1999 PType = Getter->getResultType();
2000 else {
2001 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2002 E = Setter->param_end(); PI != E; ++PI)
2003 PType = (*PI)->getType();
2004 }
2005 // FIXME: we must check that the setter has property type.
2006 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2007 Setter, MemberLoc, BaseExpr));
2008 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002009 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2010 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002011 }
Steve Naroff18bc1642008-10-20 22:53:06 +00002012 // Handle properties on qualified "id" protocols.
2013 const ObjCQualifiedIdType *QIdTy;
2014 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2015 // Check protocols on qualified interfaces.
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002016 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2017 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel)) {
2018 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002019 // Check the use of this declaration
2020 if (DiagnoseUseOfDecl(PD, MemberLoc))
2021 return ExprError();
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002022
Steve Naroff6ece14c2009-01-21 00:14:39 +00002023 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002024 MemberLoc, BaseExpr));
2025 }
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002026 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002027 // Check the use of this method.
2028 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2029 return ExprError();
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002030
Mike Stumpeed9cac2009-02-19 03:04:26 +00002031 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002032 OMD->getResultType(),
2033 OMD, OpLoc, MemberLoc,
2034 NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00002035 }
2036 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002037
2038 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2039 << &Member << BaseType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002040 }
Steve Naroffdd53eb52009-03-05 20:12:00 +00002041 // Handle properties on ObjC 'Class' types.
2042 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2043 // Also must look for a getter name which uses property syntax.
2044 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2045 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff335c6802009-03-11 20:12:18 +00002046 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2047 ObjCMethodDecl *Getter;
Steve Naroffdd53eb52009-03-05 20:12:00 +00002048 // FIXME: need to also look locally in the implementation.
Steve Naroff335c6802009-03-11 20:12:18 +00002049 if ((Getter = IFace->lookupClassMethod(Sel))) {
Steve Naroffdd53eb52009-03-05 20:12:00 +00002050 // Check the use of this method.
Steve Naroff335c6802009-03-11 20:12:18 +00002051 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffdd53eb52009-03-05 20:12:00 +00002052 return ExprError();
Steve Naroffdd53eb52009-03-05 20:12:00 +00002053 }
Steve Naroff335c6802009-03-11 20:12:18 +00002054 // If we found a getter then this may be a valid dot-reference, we
2055 // will look for the matching setter, in case it is needed.
2056 Selector SetterSel =
2057 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2058 PP.getSelectorTable(), &Member);
2059 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2060 if (!Setter) {
2061 // If this reference is in an @implementation, also check for 'private'
2062 // methods.
2063 if (ObjCImplementationDecl *ImpDecl =
2064 ObjCImplementations[IFace->getIdentifier()])
2065 Setter = ImpDecl->getInstanceMethod(SetterSel);
2066 }
2067 // Look through local category implementations associated with the class.
2068 if (!Setter) {
2069 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2070 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2071 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2072 }
2073 }
2074
2075 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2076 return ExprError();
2077
2078 if (Getter || Setter) {
2079 QualType PType;
2080
2081 if (Getter)
2082 PType = Getter->getResultType();
2083 else {
2084 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2085 E = Setter->param_end(); PI != E; ++PI)
2086 PType = (*PI)->getType();
2087 }
2088 // FIXME: we must check that the setter has property type.
2089 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2090 Setter, MemberLoc, BaseExpr));
2091 }
2092 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2093 << &Member << BaseType);
Steve Naroffdd53eb52009-03-05 20:12:00 +00002094 }
2095 }
2096
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002097 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002098 if (BaseType->isExtVectorType()) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002099 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2100 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002101 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002102 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002103 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002104 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002105
2106 return ExprError(Diag(MemberLoc,
2107 diag::err_typecheck_member_reference_struct_union)
2108 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002109}
2110
Douglas Gregor88a35142008-12-22 05:46:06 +00002111/// ConvertArgumentsForCall - Converts the arguments specified in
2112/// Args/NumArgs to the parameter types of the function FDecl with
2113/// function prototype Proto. Call is the call expression itself, and
2114/// Fn is the function expression. For a C++ member function, this
2115/// routine does not attempt to convert the object argument. Returns
2116/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002117bool
2118Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002119 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002120 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002121 Expr **Args, unsigned NumArgs,
2122 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002123 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002124 // assignment, to the types of the corresponding parameter, ...
2125 unsigned NumArgsInProto = Proto->getNumArgs();
2126 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002127 bool Invalid = false;
2128
Douglas Gregor88a35142008-12-22 05:46:06 +00002129 // If too few arguments are available (and we don't have default
2130 // arguments for the remaining parameters), don't make the call.
2131 if (NumArgs < NumArgsInProto) {
2132 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2133 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2134 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2135 // Use default arguments for missing arguments
2136 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002137 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002138 }
2139
2140 // If too many are passed and not variadic, error on the extras and drop
2141 // them.
2142 if (NumArgs > NumArgsInProto) {
2143 if (!Proto->isVariadic()) {
2144 Diag(Args[NumArgsInProto]->getLocStart(),
2145 diag::err_typecheck_call_too_many_args)
2146 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2147 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2148 Args[NumArgs-1]->getLocEnd());
2149 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002150 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002151 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002152 }
2153 NumArgsToCheck = NumArgsInProto;
2154 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002155
Douglas Gregor88a35142008-12-22 05:46:06 +00002156 // Continue to check argument types (even if we have too few/many args).
2157 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2158 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002159
Douglas Gregor88a35142008-12-22 05:46:06 +00002160 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002161 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002162 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002163
2164 // Pass the argument.
2165 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2166 return true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002167 } else
Douglas Gregor61366e92008-12-24 00:01:03 +00002168 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00002169 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00002170 QualType ArgType = Arg->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002171
Douglas Gregor88a35142008-12-22 05:46:06 +00002172 Call->setArg(i, Arg);
2173 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002174
Douglas Gregor88a35142008-12-22 05:46:06 +00002175 // If this is a variadic call, handle args passed through "...".
2176 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002177 VariadicCallType CallType = VariadicFunction;
2178 if (Fn->getType()->isBlockPointerType())
2179 CallType = VariadicBlock; // Block
2180 else if (isa<MemberExpr>(Fn))
2181 CallType = VariadicMethod;
2182
Douglas Gregor88a35142008-12-22 05:46:06 +00002183 // Promote the arguments (C99 6.5.2.2p7).
2184 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2185 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002186 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002187 Call->setArg(i, Arg);
2188 }
2189 }
2190
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002191 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002192}
2193
Steve Narofff69936d2007-09-16 03:34:24 +00002194/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002195/// This provides the location of the left/right parens and a list of comma
2196/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002197Action::OwningExprResult
2198Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2199 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002200 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002201 unsigned NumArgs = args.size();
2202 Expr *Fn = static_cast<Expr *>(fn.release());
2203 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002204 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002205 FunctionDecl *FDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002206 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00002207
Douglas Gregor88a35142008-12-22 05:46:06 +00002208 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00002209 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002210 // in which case we won't do any semantic analysis now.
Douglas Gregor17330012009-02-04 15:01:18 +00002211 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2212 bool Dependent = false;
2213 if (Fn->isTypeDependent())
2214 Dependent = true;
2215 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2216 Dependent = true;
2217
2218 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002219 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002220 Context.DependentTy, RParenLoc));
2221
2222 // Determine whether this is a call to an object (C++ [over.call.object]).
2223 if (Fn->getType()->isRecordType())
2224 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2225 CommaLocs, RParenLoc));
2226
Douglas Gregorfa047642009-02-04 00:32:51 +00002227 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00002228 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2229 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2230 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002231 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2232 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00002233 }
2234
Douglas Gregorfa047642009-02-04 00:32:51 +00002235 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00002236 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00002237 Expr *FnExpr = Fn;
2238 bool ADL = true;
2239 while (true) {
2240 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2241 FnExpr = IcExpr->getSubExpr();
2242 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002243 // Parentheses around a function disable ADL
Douglas Gregor17330012009-02-04 15:01:18 +00002244 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00002245 ADL = false;
2246 FnExpr = PExpr->getSubExpr();
2247 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00002248 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregorfa047642009-02-04 00:32:51 +00002249 == UnaryOperator::AddrOf) {
2250 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattner90e150d2009-02-14 07:22:29 +00002251 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2252 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2253 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2254 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002255 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner90e150d2009-02-14 07:22:29 +00002256 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2257 UnqualifiedName = DepName->getName();
2258 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002259 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00002260 // Any kind of name that does not refer to a declaration (or
2261 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2262 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00002263 break;
2264 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002265 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002266
Douglas Gregor17330012009-02-04 15:01:18 +00002267 OverloadedFunctionDecl *Ovl = 0;
2268 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002269 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00002270 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2271 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002272
Douglas Gregorf9201e02009-02-11 23:02:49 +00002273 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002274 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002275 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002276 ADL = false;
2277
Douglas Gregorf9201e02009-02-11 23:02:49 +00002278 // We don't perform ADL in C.
2279 if (!getLangOptions().CPlusPlus)
2280 ADL = false;
2281
Douglas Gregor17330012009-02-04 15:01:18 +00002282 if (Ovl || ADL) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002283 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2284 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002285 NumArgs, CommaLocs, RParenLoc, ADL);
2286 if (!FDecl)
2287 return ExprError();
2288
2289 // Update Fn to refer to the actual function selected.
2290 Expr *NewFn = 0;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002291 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00002292 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregorbad35182009-03-19 03:51:16 +00002293 NewFn = QualifiedDeclRefExpr::Create(Context, FDecl, FDecl->getType(),
2294 QDRExpr->getLocation(),
2295 false, false,
2296 QDRExpr->getQualifierRange(),
2297 QDRExpr->begin(),
2298 QDRExpr->size());
Douglas Gregorfa047642009-02-04 00:32:51 +00002299 else
Mike Stumpeed9cac2009-02-19 03:04:26 +00002300 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002301 Fn->getSourceRange().getBegin());
2302 Fn->Destroy(Context);
2303 Fn = NewFn;
2304 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002305 }
Chris Lattner04421082008-04-08 04:40:51 +00002306
2307 // Promote the function operand.
2308 UsualUnaryConversions(Fn);
2309
Chris Lattner925e60d2007-12-28 05:29:59 +00002310 // Make the call expr early, before semantic checks. This guarantees cleanup
2311 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002312 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2313 Args, NumArgs,
2314 Context.BoolTy,
2315 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002316
Steve Naroffdd972f22008-09-05 22:11:13 +00002317 const FunctionType *FuncT;
2318 if (!Fn->getType()->isBlockPointerType()) {
2319 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2320 // have type pointer to function".
2321 const PointerType *PT = Fn->getType()->getAsPointerType();
2322 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002323 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2324 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002325 FuncT = PT->getPointeeType()->getAsFunctionType();
2326 } else { // This is a block call.
2327 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2328 getAsFunctionType();
2329 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002330 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002331 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2332 << Fn->getType() << Fn->getSourceRange());
2333
Chris Lattner925e60d2007-12-28 05:29:59 +00002334 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002335 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002336
Douglas Gregor72564e72009-02-26 23:50:07 +00002337 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002338 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002339 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002340 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002341 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002342 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002343
Steve Naroffb291ab62007-08-28 23:30:39 +00002344 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002345 for (unsigned i = 0; i != NumArgs; i++) {
2346 Expr *Arg = Args[i];
2347 DefaultArgumentPromotion(Arg);
2348 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002349 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002351
Douglas Gregor88a35142008-12-22 05:46:06 +00002352 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2353 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002354 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2355 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002356
Chris Lattner59907c42007-08-10 20:18:51 +00002357 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00002358 if (FDecl)
2359 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00002360
Sebastian Redl0eb23302009-01-19 00:08:26 +00002361 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002362}
2363
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002364Action::OwningExprResult
2365Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2366 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002367 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002368 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002369 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002370 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002371 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002372
Eli Friedman6223c222008-05-20 05:22:08 +00002373 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002374 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002375 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2376 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor86447ec2009-03-09 16:13:40 +00002377 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002378 diag::err_typecheck_decl_incomplete_type,
2379 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002380 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002381
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002382 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002383 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002384 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002385
Chris Lattner371f2582008-12-04 23:50:19 +00002386 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002387 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002388 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002389 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002390 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002391 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002392 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002393 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002394}
2395
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002396Action::OwningExprResult
2397Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2398 InitListDesignations &Designators,
2399 SourceLocation RBraceLoc) {
2400 unsigned NumInit = initlist.size();
2401 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002402
Steve Naroff08d92e42007-09-15 18:49:24 +00002403 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00002404 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002405
Mike Stumpeed9cac2009-02-19 03:04:26 +00002406 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002407 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002408 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002409 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002410}
2411
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002412/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002413bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002414 UsualUnaryConversions(castExpr);
2415
2416 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2417 // type needs to be scalar.
2418 if (castType->isVoidType()) {
2419 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002420 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2421 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002422 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002423 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2424 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2425 (castType->isStructureType() || castType->isUnionType())) {
2426 // GCC struct/union extension: allow cast to self.
2427 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2428 << castType << castExpr->getSourceRange();
2429 } else if (castType->isUnionType()) {
2430 // GCC cast to union extension
2431 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2432 RecordDecl::field_iterator Field, FieldEnd;
2433 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2434 Field != FieldEnd; ++Field) {
2435 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2436 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2437 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2438 << castExpr->getSourceRange();
2439 break;
2440 }
2441 }
2442 if (Field == FieldEnd)
2443 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2444 << castExpr->getType() << castExpr->getSourceRange();
2445 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002446 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002447 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002448 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002449 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002450 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002451 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002452 return Diag(castExpr->getLocStart(),
2453 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002454 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002455 } else if (castExpr->getType()->isVectorType()) {
2456 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2457 return true;
2458 } else if (castType->isVectorType()) {
2459 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2460 return true;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002461 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Chris Lattnere6ee6ba2009-03-05 23:09:00 +00002462 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002463 }
2464 return false;
2465}
2466
Chris Lattnerfe23e212007-12-20 00:44:32 +00002467bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002468 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00002469
Anders Carlssona64db8f2007-11-27 05:51:55 +00002470 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002471 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002472 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00002473 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00002474 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002475 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002476 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002477 } else
2478 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002479 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002480 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002481
Anders Carlssona64db8f2007-11-27 05:51:55 +00002482 return false;
2483}
2484
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002485Action::OwningExprResult
2486Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2487 SourceLocation RParenLoc, ExprArg Op) {
2488 assert((Ty != 0) && (Op.get() != 0) &&
2489 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002490
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002491 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002492 QualType castType = QualType::getFromOpaquePtr(Ty);
2493
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002494 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002495 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002496 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002497 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002498}
2499
Sebastian Redl28507842009-02-26 14:39:58 +00002500/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2501/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002502/// C99 6.5.15
2503QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2504 SourceLocation QuestionLoc) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002505 UsualUnaryConversions(Cond);
2506 UsualUnaryConversions(LHS);
2507 UsualUnaryConversions(RHS);
2508 QualType CondTy = Cond->getType();
2509 QualType LHSTy = LHS->getType();
2510 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002511
Reid Spencer5f016e22007-07-11 17:01:13 +00002512 // first, check the condition.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002513 if (!Cond->isTypeDependent()) {
2514 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2515 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2516 << CondTy;
Douglas Gregor898574e2008-12-05 23:32:09 +00002517 return QualType();
2518 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002519 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002520
Chris Lattner70d67a92008-01-06 22:42:25 +00002521 // Now check the two expressions.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002522 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor898574e2008-12-05 23:32:09 +00002523 return Context.DependentTy;
2524
Chris Lattner70d67a92008-01-06 22:42:25 +00002525 // If both operands have arithmetic type, do the usual arithmetic conversions
2526 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002527 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2528 UsualArithmeticConversions(LHS, RHS);
2529 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00002530 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002531
Chris Lattner70d67a92008-01-06 22:42:25 +00002532 // If both operands are the same structure or union type, the result is that
2533 // type.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002534 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2535 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002536 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00002537 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00002538 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002539 return LHSTy.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002540 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002541
Chris Lattner70d67a92008-01-06 22:42:25 +00002542 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002543 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002544 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2545 if (!LHSTy->isVoidType())
2546 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2547 << RHS->getSourceRange();
2548 if (!RHSTy->isVoidType())
2549 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2550 << LHS->getSourceRange();
2551 ImpCastExprToType(LHS, Context.VoidTy);
2552 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman0e724012008-06-04 19:47:51 +00002553 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002554 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002555 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2556 // the type of the other operand."
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002557 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2558 Context.isObjCObjectPointerType(LHSTy)) &&
2559 RHS->isNullPointerConstant(Context)) {
2560 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2561 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002562 }
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002563 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2564 Context.isObjCObjectPointerType(RHSTy)) &&
2565 LHS->isNullPointerConstant(Context)) {
2566 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2567 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002568 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002569
Chris Lattnerbd57d362008-01-06 22:50:31 +00002570 // Handle the case where both operands are pointers before we handle null
2571 // pointer constants in case both operands are null pointer constants.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002572 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2573 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002574 // get the "pointed to" types
2575 QualType lhptee = LHSPT->getPointeeType();
2576 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002577
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002578 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2579 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002580 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002581 // Figure out necessary qualifiers (C99 6.5.15p6)
2582 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002583 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002584 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2585 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002586 return destType;
2587 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002588 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002589 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002590 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002591 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2592 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002593 return destType;
2594 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002595
Chris Lattnera119a3b2009-02-18 04:38:20 +00002596 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattnerb4650c12009-02-19 04:44:58 +00002597 // Two identical pointer types are always compatible.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002598 return LHSTy;
2599 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002600
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002601 QualType compositeType = LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002602
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002603 // If either type is an Objective-C object type then check
2604 // compatibility according to Objective-C.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002605 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002606 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002607 // If both operands are interfaces and either operand can be
2608 // assigned to the other, use that type as the composite
2609 // type. This allows
2610 // xxx ? (A*) a : (B*) b
2611 // where B is a subclass of A.
2612 //
2613 // Additionally, as for assignment, if either type is 'id'
2614 // allow silent coercion. Finally, if the types are
2615 // incompatible then make sure to use 'id' as the composite
2616 // type so the result is acceptable for sending messages to.
2617
Steve Naroff1fd03612009-02-12 19:05:07 +00002618 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002619 // It could return the composite type.
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002620 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2621 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2622 if (LHSIface && RHSIface &&
2623 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002624 compositeType = LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002625 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002626 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002627 compositeType = RHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002628 } else if (Context.isObjCIdStructType(lhptee) ||
2629 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002630 compositeType = Context.getObjCIdType();
2631 } else {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002632 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stumpeed9cac2009-02-19 03:04:26 +00002633 << LHSTy << RHSTy
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002634 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002635 QualType incompatTy = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002636 ImpCastExprToType(LHS, incompatTy);
2637 ImpCastExprToType(RHS, incompatTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002638 return incompatTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002639 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002640 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002641 rhptee.getUnqualifiedType())) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002642 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2643 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002644 // In this situation, we assume void* type. No especially good
2645 // reason, but this is what gcc does, and we do have to pick
2646 // to get a consistent AST.
2647 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002648 ImpCastExprToType(LHS, incompatTy);
2649 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002650 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002651 }
2652 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002653 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2654 // differently qualified versions of compatible types, the result type is
2655 // a pointer to an appropriately qualified version of the *composite*
2656 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002657 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002658 // FIXME: Need to add qualifiers
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002659 ImpCastExprToType(LHS, compositeType);
2660 ImpCastExprToType(RHS, compositeType);
Eli Friedman5835ea22008-05-16 20:37:07 +00002661 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 }
2663 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002664
Chris Lattnera119a3b2009-02-18 04:38:20 +00002665 // Selection between block pointer types is ok as long as they are the same.
2666 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2667 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2668 return LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002669
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002670 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2671 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stumpeed9cac2009-02-19 03:04:26 +00002672 // id with statically typed objects).
2673 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002674 // GCC allows qualified id and any Objective-C type to devolve to
2675 // id. Currently localizing to here until clear this should be
2676 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002677 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00002678 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002679 Context.isObjCObjectPointerType(RHSTy)) ||
2680 (RHSTy->isObjCQualifiedIdType() &&
2681 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002682 // FIXME: This is not the correct composite type. This only
2683 // happens to work because id can more or less be used anywhere,
2684 // however this may change the type of method sends.
2685 // FIXME: gcc adds some type-checking of the arguments and emits
2686 // (confusing) incompatible comparison warnings in some
2687 // cases. Investigate.
2688 QualType compositeType = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002689 ImpCastExprToType(LHS, compositeType);
2690 ImpCastExprToType(RHS, compositeType);
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002691 return compositeType;
2692 }
2693 }
2694
Chris Lattner70d67a92008-01-06 22:42:25 +00002695 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002696 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2697 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 return QualType();
2699}
2700
Steve Narofff69936d2007-09-16 03:34:24 +00002701/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002702/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002703Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2704 SourceLocation ColonLoc,
2705 ExprArg Cond, ExprArg LHS,
2706 ExprArg RHS) {
2707 Expr *CondExpr = (Expr *) Cond.get();
2708 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002709
2710 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2711 // was the condition.
2712 bool isLHSNull = LHSExpr == 0;
2713 if (isLHSNull)
2714 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002715
2716 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002717 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002719 return ExprError();
2720
2721 Cond.release();
2722 LHS.release();
2723 RHS.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002724 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002725 isLHSNull ? 0 : LHSExpr,
2726 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002727}
2728
Reid Spencer5f016e22007-07-11 17:01:13 +00002729
2730// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00002731// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00002732// routine is it effectively iqnores the qualifiers on the top level pointee.
2733// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2734// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002735Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002736Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2737 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002738
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002740 lhptee = lhsType->getAsPointerType()->getPointeeType();
2741 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002742
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002744 lhptee = Context.getCanonicalType(lhptee);
2745 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002746
Chris Lattner5cf216b2008-01-04 18:04:52 +00002747 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002748
2749 // C99 6.5.16.1p1: This following citation is common to constraints
2750 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2751 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002752 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002753 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002754 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002755
Mike Stumpeed9cac2009-02-19 03:04:26 +00002756 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2757 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002759 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002760 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002761 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002762
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002763 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002764 assert(rhptee->isFunctionType());
2765 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002766 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002767
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002768 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002769 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002770 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002771
2772 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002773 assert(lhptee->isFunctionType());
2774 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002775 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002776 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 // unqualified versions of compatible types, ...
Mike Stumpeed9cac2009-02-19 03:04:26 +00002778 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002779 rhptee.getUnqualifiedType()))
2780 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002781 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002782}
2783
Steve Naroff1c7d0672008-09-04 15:10:53 +00002784/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2785/// block pointer types are compatible or whether a block and normal pointer
2786/// are compatible. It is more restrict than comparing two function pointer
2787// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002788Sema::AssignConvertType
2789Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00002790 QualType rhsType) {
2791 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002792
Steve Naroff1c7d0672008-09-04 15:10:53 +00002793 // get the "pointed to" type (ignoring qualifiers at the top level)
2794 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002795 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2796
Steve Naroff1c7d0672008-09-04 15:10:53 +00002797 // make sure we operate on the canonical type
2798 lhptee = Context.getCanonicalType(lhptee);
2799 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002800
Steve Naroff1c7d0672008-09-04 15:10:53 +00002801 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002802
Steve Naroff1c7d0672008-09-04 15:10:53 +00002803 // For blocks we enforce that qualifiers are identical.
2804 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2805 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002806
Steve Naroff1c7d0672008-09-04 15:10:53 +00002807 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002808 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002809 return ConvTy;
2810}
2811
Mike Stumpeed9cac2009-02-19 03:04:26 +00002812/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2813/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00002814/// pointers. Here are some objectionable examples that GCC considers warnings:
2815///
2816/// int a, *pint;
2817/// short *pshort;
2818/// struct foo *pfoo;
2819///
2820/// pint = pshort; // warning: assignment from incompatible pointer type
2821/// a = pint; // warning: assignment makes integer from pointer without a cast
2822/// pint = a; // warning: assignment makes pointer from integer without a cast
2823/// pint = pfoo; // warning: assignment from incompatible pointer type
2824///
2825/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00002826/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002827///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002828Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002829Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002830 // Get canonical types. We're not formatting these types, just comparing
2831 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002832 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2833 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002834
2835 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002836 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002837
Douglas Gregor9d293df2008-10-28 00:22:11 +00002838 // If the left-hand side is a reference type, then we are in a
2839 // (rare!) case where we've allowed the use of references in C,
2840 // e.g., as a parameter type in a built-in function. In this case,
2841 // just make sure that the type referenced is compatible with the
2842 // right-hand side type. The caller is responsible for adjusting
2843 // lhsType so that the resulting expression does not have reference
2844 // type.
2845 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2846 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002847 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002848 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002849 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002850
Chris Lattnereca7be62008-04-07 05:30:13 +00002851 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2852 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002853 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002854 // Relax integer conversions like we do for pointers below.
2855 if (rhsType->isIntegerType())
2856 return IntToPointer;
2857 if (lhsType->isIntegerType())
2858 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002859 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002860 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002861
Nate Begemanbe2341d2008-07-14 18:02:46 +00002862 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002863 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002864 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2865 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002866 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002867
Nate Begemanbe2341d2008-07-14 18:02:46 +00002868 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00002869 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00002870 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002871 if (getLangOptions().LaxVectorConversions &&
2872 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002873 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002874 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002875 }
2876 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002877 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002878
Chris Lattnere8b3e962008-01-04 23:32:24 +00002879 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002880 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002881
Chris Lattner78eca282008-04-07 06:49:41 +00002882 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002883 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002884 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002885
Chris Lattner78eca282008-04-07 06:49:41 +00002886 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002887 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002888
Steve Naroffb4406862008-09-29 18:10:17 +00002889 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002890 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002891 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002892
2893 // Treat block pointers as objects.
2894 if (getLangOptions().ObjC1 &&
2895 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2896 return Compatible;
2897 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002898 return Incompatible;
2899 }
2900
2901 if (isa<BlockPointerType>(lhsType)) {
2902 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00002903 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002904
Steve Naroffb4406862008-09-29 18:10:17 +00002905 // Treat block pointers as objects.
2906 if (getLangOptions().ObjC1 &&
2907 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2908 return Compatible;
2909
Steve Naroff1c7d0672008-09-04 15:10:53 +00002910 if (rhsType->isBlockPointerType())
2911 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002912
Steve Naroff1c7d0672008-09-04 15:10:53 +00002913 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2914 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002915 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002916 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002917 return Incompatible;
2918 }
2919
Chris Lattner78eca282008-04-07 06:49:41 +00002920 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002921 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002922 if (lhsType == Context.BoolTy)
2923 return Compatible;
2924
2925 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002926 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002927
Mike Stumpeed9cac2009-02-19 03:04:26 +00002928 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002929 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002930
2931 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff1c7d0672008-09-04 15:10:53 +00002932 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002933 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002934 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002935 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002936
Chris Lattnerfc144e22008-01-04 23:18:45 +00002937 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002938 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002939 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002940 }
2941 return Incompatible;
2942}
2943
Chris Lattner5cf216b2008-01-04 18:04:52 +00002944Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002945Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002946 if (getLangOptions().CPlusPlus) {
2947 if (!lhsType->isRecordType()) {
2948 // C++ 5.17p3: If the left operand is not of class type, the
2949 // expression is implicitly converted (C++ 4) to the
2950 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002951 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2952 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002953 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002954 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002955 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002956 }
2957
2958 // FIXME: Currently, we fall through and treat C++ classes like C
2959 // structures.
2960 }
2961
Steve Naroff529a4ad2007-11-27 17:58:44 +00002962 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2963 // a null pointer constant.
Steve Narofff7f52e72009-02-21 21:17:01 +00002964 if ((lhsType->isPointerType() ||
2965 lhsType->isObjCQualifiedIdType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00002966 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002967 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002968 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002969 return Compatible;
2970 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002971
Chris Lattner943140e2007-10-16 02:55:40 +00002972 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002973 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002974 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002975 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002976 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00002977 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002978 if (!lhsType->isReferenceType())
2979 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002980
Chris Lattner5cf216b2008-01-04 18:04:52 +00002981 Sema::AssignConvertType result =
2982 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00002983
Steve Narofff1120de2007-08-24 22:33:52 +00002984 // C99 6.5.16.1p2: The value of the right operand is converted to the
2985 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002986 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2987 // so that we can use references in built-in functions even in C.
2988 // The getNonReferenceType() call makes sure that the resulting expression
2989 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002990 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002991 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002992 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002993}
2994
Chris Lattner5cf216b2008-01-04 18:04:52 +00002995Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002996Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2997 return CheckAssignmentConstraints(lhsType, rhsType);
2998}
2999
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003000QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003001 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00003002 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003003 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00003004 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003005}
3006
Mike Stumpeed9cac2009-02-19 03:04:26 +00003007inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00003008 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003009 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003010 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003011 QualType lhsType =
3012 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3013 QualType rhsType =
3014 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003015
Nate Begemanbe2341d2008-07-14 18:02:46 +00003016 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003017 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00003019
Nate Begemanbe2341d2008-07-14 18:02:46 +00003020 // Handle the case of a vector & extvector type of the same size and element
3021 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003022 if (getLangOptions().LaxVectorConversions) {
3023 // FIXME: Should we warn here?
3024 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003025 if (const VectorType *RV = rhsType->getAsVectorType())
3026 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003027 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003028 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003029 }
3030 }
3031 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003032
Nate Begemanbe2341d2008-07-14 18:02:46 +00003033 // If the lhs is an extended vector and the rhs is a scalar of the same type
3034 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00003035 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003036 QualType eltType = V->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003037
3038 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00003039 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3040 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003041 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00003042 return lhsType;
3043 }
3044 }
3045
Nate Begemanbe2341d2008-07-14 18:02:46 +00003046 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00003047 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00003048 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003049 QualType eltType = V->getElementType();
3050
Mike Stumpeed9cac2009-02-19 03:04:26 +00003051 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00003052 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3053 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003054 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00003055 return rhsType;
3056 }
3057 }
3058
Reid Spencer5f016e22007-07-11 17:01:13 +00003059 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003060 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00003061 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003062 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00003064}
3065
Reid Spencer5f016e22007-07-11 17:01:13 +00003066inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003067 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003068{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00003069 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003070 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003071
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003072 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003073
Steve Naroffa4332e22007-07-17 00:58:39 +00003074 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003075 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003076 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003077}
3078
3079inline QualType Sema::CheckRemainderOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003080 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003081{
Daniel Dunbar523aa602009-01-05 22:55:36 +00003082 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3083 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3084 return CheckVectorOperands(Loc, lex, rex);
3085 return InvalidOperands(Loc, lex, rex);
3086 }
Steve Naroff90045e82007-07-13 23:32:42 +00003087
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003088 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003089
Steve Naroffa4332e22007-07-17 00:58:39 +00003090 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003091 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003092 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003093}
3094
3095inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stumpeed9cac2009-02-19 03:04:26 +00003096 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003097{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003098 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003099 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00003100
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003101 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00003102
Reid Spencer5f016e22007-07-11 17:01:13 +00003103 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00003104 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003105 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003106
Eli Friedmand72d16e2008-05-18 18:08:51 +00003107 // Put any potential pointer into PExp
3108 Expr* PExp = lex, *IExp = rex;
3109 if (IExp->getType()->isPointerType())
3110 std::swap(PExp, IExp);
3111
3112 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3113 if (IExp->getType()->isIntegerType()) {
3114 // Check for arithmetic on pointers to incomplete types
3115 if (!PTy->getPointeeType()->isObjectType()) {
3116 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003117 if (getLangOptions().CPlusPlus) {
3118 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3119 << lex->getSourceRange() << rex->getSourceRange();
3120 return QualType();
3121 }
3122
3123 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003124 Diag(Loc, diag::ext_gnu_void_ptr)
3125 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003126 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003127 if (getLangOptions().CPlusPlus) {
3128 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3129 << lex->getType() << lex->getSourceRange();
3130 return QualType();
3131 }
3132
3133 // GNU extension: arithmetic on pointer to function
3134 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003135 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003136 } else {
Douglas Gregor86447ec2009-03-09 16:13:40 +00003137 RequireCompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003138 diag::err_typecheck_arithmetic_incomplete_type,
3139 lex->getSourceRange(), SourceRange(),
3140 lex->getType());
3141 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00003142 }
3143 }
3144 return PExp->getType();
3145 }
3146 }
3147
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003148 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003149}
3150
Chris Lattnereca7be62008-04-07 05:30:13 +00003151// C99 6.5.6
3152QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003153 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00003154 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003155 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003156
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003157 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003158
Chris Lattner6e4ab612007-12-09 21:53:25 +00003159 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003160
Chris Lattner6e4ab612007-12-09 21:53:25 +00003161 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00003162 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003163 return compType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003164
Chris Lattner6e4ab612007-12-09 21:53:25 +00003165 // Either ptr - int or ptr - ptr.
3166 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00003167 QualType lpointee = LHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003168
Chris Lattner6e4ab612007-12-09 21:53:25 +00003169 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00003170 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00003171 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00003172 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003173 Diag(Loc, diag::ext_gnu_void_ptr)
3174 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00003175 } else if (lpointee->isFunctionType()) {
3176 if (getLangOptions().CPlusPlus) {
3177 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3178 << lex->getType() << lex->getSourceRange();
3179 return QualType();
3180 }
3181
3182 // GNU extension: arithmetic on pointer to function
3183 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3184 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003185 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003186 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00003187 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003188 return QualType();
3189 }
3190 }
3191
3192 // The result type of a pointer-int computation is the pointer type.
3193 if (rex->getType()->isIntegerType())
3194 return lex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003195
Chris Lattner6e4ab612007-12-09 21:53:25 +00003196 // Handle pointer-pointer subtractions.
3197 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00003198 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003199
Chris Lattner6e4ab612007-12-09 21:53:25 +00003200 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00003201 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00003202 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00003203 if (rpointee->isVoidType()) {
3204 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003205 Diag(Loc, diag::ext_gnu_void_ptr)
3206 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00003207 } else if (rpointee->isFunctionType()) {
3208 if (getLangOptions().CPlusPlus) {
3209 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3210 << rex->getType() << rex->getSourceRange();
3211 return QualType();
3212 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003213
Douglas Gregor08048882009-01-23 19:03:35 +00003214 // GNU extension: arithmetic on pointer to function
3215 if (!lpointee->isFunctionType())
3216 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3217 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003218 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003219 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00003220 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003221 return QualType();
3222 }
3223 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003224
Chris Lattner6e4ab612007-12-09 21:53:25 +00003225 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003226 if (!Context.typesAreCompatible(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003227 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003228 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003229 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00003230 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003231 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003232 return QualType();
3233 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003234
Chris Lattner6e4ab612007-12-09 21:53:25 +00003235 return Context.getPointerDiffType();
3236 }
3237 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003238
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003239 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003240}
3241
Chris Lattnereca7be62008-04-07 05:30:13 +00003242// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003243QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003244 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00003245 // C99 6.5.7p2: Each of the operands shall have integer type.
3246 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003247 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003248
Chris Lattnerca5eede2007-12-12 05:47:28 +00003249 // Shifts don't perform usual arithmetic conversions, they just do integer
3250 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00003251 if (!isCompAssign)
3252 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00003253 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003254
Chris Lattnerca5eede2007-12-12 05:47:28 +00003255 // "The type of the result is that of the promoted left operand."
3256 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003257}
3258
Chris Lattnereca7be62008-04-07 05:30:13 +00003259// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003260QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003261 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003262 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003263 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003264
Chris Lattnera5937dd2007-08-26 01:18:55 +00003265 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00003266 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3267 UsualArithmeticConversions(lex, rex);
3268 else {
3269 UsualUnaryConversions(lex);
3270 UsualUnaryConversions(rex);
3271 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003272 QualType lType = lex->getType();
3273 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003274
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003275 if (!lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00003276 // For non-floating point types, check for self-comparisons of the form
3277 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3278 // often indicate logic errors in the program.
Ted Kremenekb82dcd82009-03-20 18:35:45 +00003279 // NOTE: Per <rdar://problem/6703892>, don't warn about comparisons of enum
3280 // constants. These can arise from macro expansions, and are usually quite
3281 // deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00003282 Expr *LHSStripped = lex->IgnoreParens();
3283 Expr *RHSStripped = rex->IgnoreParens();
3284 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3285 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00003286 if (DRL->getDecl() == DRR->getDecl() &&
3287 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003288 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner55660a72009-03-08 19:39:53 +00003289
3290 if (isa<CastExpr>(LHSStripped))
3291 LHSStripped = LHSStripped->IgnoreParenCasts();
3292 if (isa<CastExpr>(RHSStripped))
3293 RHSStripped = RHSStripped->IgnoreParenCasts();
3294
3295 // Warn about comparisons against a string constant (unless the other
3296 // operand is null), the user probably wants strcmp.
3297 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3298 !RHSStripped->isNullPointerConstant(Context))
3299 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3300 else if ((isa<StringLiteral>(RHSStripped) ||
3301 isa<ObjCEncodeExpr>(RHSStripped)) &&
3302 !LHSStripped->isNullPointerConstant(Context))
3303 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003304 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003305
Douglas Gregor447b69e2008-11-19 03:25:36 +00003306 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00003307 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00003308
Chris Lattnera5937dd2007-08-26 01:18:55 +00003309 if (isRelational) {
3310 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003311 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003312 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003313 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003314 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00003315 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003316 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00003317 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003318
Chris Lattnera5937dd2007-08-26 01:18:55 +00003319 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003320 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003321 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003322
Chris Lattnerd28f8152007-08-26 01:10:14 +00003323 bool LHSIsNull = lex->isNullPointerConstant(Context);
3324 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003325
Chris Lattnera5937dd2007-08-26 01:18:55 +00003326 // All of the following pointer related warnings are GCC extensions, except
3327 // when handling null pointer constants. One day, we can consider making them
3328 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00003329 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003330 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003331 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00003332 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003333 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003334
Steve Naroff66296cb2007-11-13 14:57:38 +00003335 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003336 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3337 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00003338 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff389bf462009-02-12 17:52:19 +00003339 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003340 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003341 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003342 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00003343 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003344 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003345 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003346 // Handle block pointer types.
3347 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3348 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3349 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003350
Steve Naroff1c7d0672008-09-04 15:10:53 +00003351 if (!LHSIsNull && !RHSIsNull &&
3352 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003353 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003354 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00003355 }
3356 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003357 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003358 }
Steve Naroff59f53942008-09-28 01:11:11 +00003359 // Allow block pointers to be compared with null pointer constants.
3360 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3361 (lType->isPointerType() && rType->isBlockPointerType())) {
3362 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003363 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003364 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00003365 }
3366 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003367 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00003368 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003369
Steve Naroff20373222008-06-03 14:04:54 +00003370 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00003371 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00003372 const PointerType *LPT = lType->getAsPointerType();
3373 const PointerType *RPT = rType->getAsPointerType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003374 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003375 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003376 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003377 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003378
Steve Naroffa8069f12008-11-17 19:49:16 +00003379 if (!LPtrToVoid && !RPtrToVoid &&
3380 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003381 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003382 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00003383 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003384 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00003385 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003386 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003387 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00003388 }
Steve Naroff20373222008-06-03 14:04:54 +00003389 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3390 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003391 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003392 } else {
3393 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003394 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003395 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003396 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003397 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003398 }
Steve Naroff20373222008-06-03 14:04:54 +00003399 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00003400 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003401 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff20373222008-06-03 14:04:54 +00003402 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003403 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003404 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003405 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003406 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003407 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003408 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003409 if (lType->isIntegerType() &&
Steve Naroff20373222008-06-03 14:04:54 +00003410 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003411 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003412 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003413 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003414 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003415 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003416 }
Steve Naroff39218df2008-09-04 16:56:14 +00003417 // Handle block pointers.
3418 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3419 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003420 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003421 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003422 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003423 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003424 }
3425 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3426 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003427 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003428 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003429 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003430 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003431 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003432 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003433}
3434
Nate Begemanbe2341d2008-07-14 18:02:46 +00003435/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00003436/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003437/// like a scalar comparison, a vector comparison produces a vector of integer
3438/// types.
3439QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003440 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003441 bool isRelational) {
3442 // Check to make sure we're operating on vectors of the same type and width,
3443 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003444 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003445 if (vType.isNull())
3446 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003447
Nate Begemanbe2341d2008-07-14 18:02:46 +00003448 QualType lType = lex->getType();
3449 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003450
Nate Begemanbe2341d2008-07-14 18:02:46 +00003451 // For non-floating point types, check for self-comparisons of the form
3452 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3453 // often indicate logic errors in the program.
3454 if (!lType->isFloatingType()) {
3455 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3456 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3457 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003458 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003459 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003460
Nate Begemanbe2341d2008-07-14 18:02:46 +00003461 // Check for comparisons of floating point operands using != and ==.
3462 if (!isRelational && lType->isFloatingType()) {
3463 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003464 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003465 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003466
Nate Begemanbe2341d2008-07-14 18:02:46 +00003467 // Return the type for the comparison, which is the same as vector type for
3468 // integer vectors, or an integer type of identical size and number of
3469 // elements for floating point vectors.
3470 if (lType->isIntegerType())
3471 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003472
Nate Begemanbe2341d2008-07-14 18:02:46 +00003473 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003474 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003475 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003476 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003477 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3478 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3479
Mike Stumpeed9cac2009-02-19 03:04:26 +00003480 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00003481 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003482 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3483}
3484
Reid Spencer5f016e22007-07-11 17:01:13 +00003485inline QualType Sema::CheckBitwiseOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003486 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003487{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003488 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003489 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003490
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003491 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003492
Steve Naroffa4332e22007-07-17 00:58:39 +00003493 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003494 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003495 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003496}
3497
3498inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stumpeed9cac2009-02-19 03:04:26 +00003499 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003500{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003501 UsualUnaryConversions(lex);
3502 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003503
Eli Friedman5773a6c2008-05-13 20:16:47 +00003504 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003505 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003506 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003507}
3508
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003509/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3510/// is a read-only property; return true if so. A readonly property expression
3511/// depends on various declarations and thus must be treated specially.
3512///
Mike Stumpeed9cac2009-02-19 03:04:26 +00003513static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003514{
3515 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3516 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3517 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3518 QualType BaseType = PropExpr->getBase()->getType();
3519 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003520 if (const ObjCInterfaceType *IFTy =
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003521 PTy->getPointeeType()->getAsObjCInterfaceType())
3522 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3523 if (S.isPropertyReadonly(PDecl, IFace))
3524 return true;
3525 }
3526 }
3527 return false;
3528}
3529
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003530/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3531/// emit an error and return true. If so, return false.
3532static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003533 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3534 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3535 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003536 if (IsLV == Expr::MLV_Valid)
3537 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003538
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003539 unsigned Diag = 0;
3540 bool NeedType = false;
3541 switch (IsLV) { // C99 6.5.16p2
3542 default: assert(0 && "Unknown result from isModifiableLvalue!");
3543 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003544 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003545 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3546 NeedType = true;
3547 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003548 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003549 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3550 NeedType = true;
3551 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003552 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003553 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3554 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003555 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003556 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3557 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003558 case Expr::MLV_IncompleteType:
3559 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00003560 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003561 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3562 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003563 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003564 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3565 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003566 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003567 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3568 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003569 case Expr::MLV_ReadonlyProperty:
3570 Diag = diag::error_readonly_property_assignment;
3571 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003572 case Expr::MLV_NoSetterProperty:
3573 Diag = diag::error_nosetter_property_assignment;
3574 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003575 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003576
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003577 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003578 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003579 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003580 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003581 return true;
3582}
3583
3584
3585
3586// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003587QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3588 SourceLocation Loc,
3589 QualType CompoundType) {
3590 // Verify that LHS is a modifiable lvalue, and emit error if not.
3591 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003592 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003593
3594 QualType LHSType = LHS->getType();
3595 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003596
Chris Lattner5cf216b2008-01-04 18:04:52 +00003597 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003598 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003599 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003600 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003601 // Special case of NSObject attributes on c-style pointer types.
3602 if (ConvTy == IncompatiblePointer &&
3603 ((Context.isObjCNSObjectType(LHSType) &&
3604 Context.isObjCObjectPointerType(RHSType)) ||
3605 (Context.isObjCNSObjectType(RHSType) &&
3606 Context.isObjCObjectPointerType(LHSType))))
3607 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003608
Chris Lattner2c156472008-08-21 18:04:13 +00003609 // If the RHS is a unary plus or minus, check to see if they = and + are
3610 // right next to each other. If so, the user may have typo'd "x =+ 4"
3611 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003612 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003613 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3614 RHSCheck = ICE->getSubExpr();
3615 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3616 if ((UO->getOpcode() == UnaryOperator::Plus ||
3617 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003618 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003619 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00003620 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3621 // And there is a space or other character before the subexpr of the
3622 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00003623 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3624 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003625 Diag(Loc, diag::warn_not_compound_assign)
3626 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3627 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00003628 }
Chris Lattner2c156472008-08-21 18:04:13 +00003629 }
3630 } else {
3631 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003632 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003633 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003634
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003635 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3636 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003637 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003638
Reid Spencer5f016e22007-07-11 17:01:13 +00003639 // C99 6.5.16p3: The type of an assignment expression is the type of the
3640 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00003641 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00003642 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3643 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003644 // C++ 5.17p1: the type of the assignment expression is that of its left
3645 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003646 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003647}
3648
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003649// C99 6.5.17
3650QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3651 // FIXME: what is required for LHS?
Mike Stumpeed9cac2009-02-19 03:04:26 +00003652
Chris Lattner53fcaa92008-07-25 20:54:07 +00003653 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003654 DefaultFunctionArrayConversion(RHS);
3655 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003656}
3657
Steve Naroff49b45262007-07-13 16:58:59 +00003658/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3659/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003660QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3661 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003662 if (Op->isTypeDependent())
3663 return Context.DependentTy;
3664
Chris Lattner3528d352008-11-21 07:05:48 +00003665 QualType ResType = Op->getType();
3666 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003667
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003668 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3669 // Decrement of bool is not allowed.
3670 if (!isInc) {
3671 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3672 return QualType();
3673 }
3674 // Increment of bool sets it to true, but is deprecated.
3675 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3676 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003677 // OK!
3678 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3679 // C99 6.5.2.4p2, 6.5.6p2
3680 if (PT->getPointeeType()->isObjectType()) {
3681 // Pointer to object is ok!
3682 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003683 if (getLangOptions().CPlusPlus) {
3684 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3685 << Op->getSourceRange();
3686 return QualType();
3687 }
3688
3689 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003690 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003691 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003692 if (getLangOptions().CPlusPlus) {
3693 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3694 << Op->getType() << Op->getSourceRange();
3695 return QualType();
3696 }
3697
3698 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003699 << ResType << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003700 } else {
Douglas Gregor86447ec2009-03-09 16:13:40 +00003701 RequireCompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003702 diag::err_typecheck_arithmetic_incomplete_type,
3703 Op->getSourceRange(), SourceRange(),
3704 ResType);
3705 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003706 }
Chris Lattner3528d352008-11-21 07:05:48 +00003707 } else if (ResType->isComplexType()) {
3708 // C99 does not support ++/-- on complex types, we allow as an extension.
3709 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003710 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003711 } else {
3712 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003713 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003714 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003715 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003716 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00003717 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003718 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003719 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003720 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003721}
3722
Anders Carlsson369dee42008-02-01 07:15:58 +00003723/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003724/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003725/// where the declaration is needed for type checking. We only need to
3726/// handle cases when the expression references a function designator
3727/// or is an lvalue. Here are some examples:
3728/// - &(x) => x
3729/// - &*****f => f for f a function designator.
3730/// - &s.xx => s
3731/// - &s.zz[1].yy -> s, if zz is an array
3732/// - *(x + 1) -> x, if x is an array
3733/// - &"123"[2] -> 0
3734/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003735static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003736 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003737 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003738 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003739 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003740 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003741 // Fields cannot be declared with a 'register' storage class.
3742 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003743 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003744 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003745 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003746 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003747 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003748
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003749 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003750 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003751 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003752 return 0;
3753 else
3754 return VD;
3755 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003756 case Stmt::UnaryOperatorClass: {
3757 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003758
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003759 switch(UO->getOpcode()) {
3760 case UnaryOperator::Deref: {
3761 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003762 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3763 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3764 if (!VD || VD->getType()->isPointerType())
3765 return 0;
3766 return VD;
3767 }
3768 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003769 }
3770 case UnaryOperator::Real:
3771 case UnaryOperator::Imag:
3772 case UnaryOperator::Extension:
3773 return getPrimaryDecl(UO->getSubExpr());
3774 default:
3775 return 0;
3776 }
3777 }
3778 case Stmt::BinaryOperatorClass: {
3779 BinaryOperator *BO = cast<BinaryOperator>(E);
3780
3781 // Handle cases involving pointer arithmetic. The result of an
3782 // Assign or AddAssign is not an lvalue so they can be ignored.
3783
3784 // (x + n) or (n + x) => x
3785 if (BO->getOpcode() == BinaryOperator::Add) {
3786 if (BO->getLHS()->getType()->isPointerType()) {
3787 return getPrimaryDecl(BO->getLHS());
3788 } else if (BO->getRHS()->getType()->isPointerType()) {
3789 return getPrimaryDecl(BO->getRHS());
3790 }
3791 }
3792
3793 return 0;
3794 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003795 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003796 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003797 case Stmt::ImplicitCastExprClass:
3798 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003799 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003800 default:
3801 return 0;
3802 }
3803}
3804
3805/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00003806/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00003807/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003808/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00003809/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003810/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00003811/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003812QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003813 if (op->isTypeDependent())
3814 return Context.DependentTy;
3815
Steve Naroff08f19672008-01-13 17:10:08 +00003816 if (getLangOptions().C99) {
3817 // Implement C99-only parts of addressof rules.
3818 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3819 if (uOp->getOpcode() == UnaryOperator::Deref)
3820 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3821 // (assuming the deref expression is valid).
3822 return uOp->getSubExpr()->getType();
3823 }
3824 // Technically, there should be a check for array subscript
3825 // expressions here, but the result of one is always an lvalue anyway.
3826 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003827 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003828 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003829
Reid Spencer5f016e22007-07-11 17:01:13 +00003830 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003831 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3832 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003833 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3834 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003835 return QualType();
3836 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003837 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003838 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3839 if (Field->isBitField()) {
3840 Diag(OpLoc, diag::err_typecheck_address_of)
3841 << "bit-field" << op->getSourceRange();
3842 return QualType();
3843 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003844 }
3845 // Check for Apple extension for accessing vector components.
Nate Begemanb104b1f2009-02-15 22:45:20 +00003846 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3847 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003848 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00003849 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003850 return QualType();
3851 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00003852 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00003853 // with the register storage-class specifier.
3854 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3855 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003856 Diag(OpLoc, diag::err_typecheck_address_of)
3857 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003858 return QualType();
3859 }
Douglas Gregor29882052008-12-10 21:26:49 +00003860 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003861 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003862 } else if (isa<FieldDecl>(dcl)) {
3863 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00003864 // Could be a pointer to member, though, if there is an explicit
3865 // scope qualifier for the class.
3866 if (isa<QualifiedDeclRefExpr>(op)) {
3867 DeclContext *Ctx = dcl->getDeclContext();
3868 if (Ctx && Ctx->isRecord())
3869 return Context.getMemberPointerType(op->getType(),
3870 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3871 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003872 } else if (isa<FunctionDecl>(dcl)) {
3873 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00003874 // As above.
3875 if (isa<QualifiedDeclRefExpr>(op)) {
3876 DeclContext *Ctx = dcl->getDeclContext();
3877 if (Ctx && Ctx->isRecord())
3878 return Context.getMemberPointerType(op->getType(),
3879 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3880 }
Douglas Gregor29882052008-12-10 21:26:49 +00003881 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003882 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003883 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003884 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00003885
Reid Spencer5f016e22007-07-11 17:01:13 +00003886 // If the operand has type "type", the result has type "pointer to type".
3887 return Context.getPointerType(op->getType());
3888}
3889
Chris Lattner22caddc2008-11-23 09:13:29 +00003890QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003891 if (Op->isTypeDependent())
3892 return Context.DependentTy;
3893
Chris Lattner22caddc2008-11-23 09:13:29 +00003894 UsualUnaryConversions(Op);
3895 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003896
Chris Lattner22caddc2008-11-23 09:13:29 +00003897 // Note that per both C89 and C99, this is always legal, even if ptype is an
3898 // incomplete type or void. It would be possible to warn about dereferencing
3899 // a void pointer, but it's completely well-defined, and such a warning is
3900 // unlikely to catch any mistakes.
3901 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003902 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003903
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003904 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003905 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003906 return QualType();
3907}
3908
3909static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3910 tok::TokenKind Kind) {
3911 BinaryOperator::Opcode Opc;
3912 switch (Kind) {
3913 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00003914 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3915 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003916 case tok::star: Opc = BinaryOperator::Mul; break;
3917 case tok::slash: Opc = BinaryOperator::Div; break;
3918 case tok::percent: Opc = BinaryOperator::Rem; break;
3919 case tok::plus: Opc = BinaryOperator::Add; break;
3920 case tok::minus: Opc = BinaryOperator::Sub; break;
3921 case tok::lessless: Opc = BinaryOperator::Shl; break;
3922 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3923 case tok::lessequal: Opc = BinaryOperator::LE; break;
3924 case tok::less: Opc = BinaryOperator::LT; break;
3925 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3926 case tok::greater: Opc = BinaryOperator::GT; break;
3927 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3928 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3929 case tok::amp: Opc = BinaryOperator::And; break;
3930 case tok::caret: Opc = BinaryOperator::Xor; break;
3931 case tok::pipe: Opc = BinaryOperator::Or; break;
3932 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3933 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3934 case tok::equal: Opc = BinaryOperator::Assign; break;
3935 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3936 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3937 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3938 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3939 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3940 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3941 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3942 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3943 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3944 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3945 case tok::comma: Opc = BinaryOperator::Comma; break;
3946 }
3947 return Opc;
3948}
3949
3950static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3951 tok::TokenKind Kind) {
3952 UnaryOperator::Opcode Opc;
3953 switch (Kind) {
3954 default: assert(0 && "Unknown unary op!");
3955 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3956 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3957 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3958 case tok::star: Opc = UnaryOperator::Deref; break;
3959 case tok::plus: Opc = UnaryOperator::Plus; break;
3960 case tok::minus: Opc = UnaryOperator::Minus; break;
3961 case tok::tilde: Opc = UnaryOperator::Not; break;
3962 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003963 case tok::kw___real: Opc = UnaryOperator::Real; break;
3964 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3965 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3966 }
3967 return Opc;
3968}
3969
Douglas Gregoreaebc752008-11-06 23:29:22 +00003970/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3971/// operator @p Opc at location @c TokLoc. This routine only supports
3972/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003973Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3974 unsigned Op,
3975 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003976 QualType ResultTy; // Result type of the binary operator.
3977 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3978 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3979
3980 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003981 case BinaryOperator::Assign:
3982 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3983 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003984 case BinaryOperator::PtrMemD:
3985 case BinaryOperator::PtrMemI:
3986 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3987 Opc == BinaryOperator::PtrMemI);
3988 break;
3989 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003990 case BinaryOperator::Div:
3991 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3992 break;
3993 case BinaryOperator::Rem:
3994 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3995 break;
3996 case BinaryOperator::Add:
3997 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3998 break;
3999 case BinaryOperator::Sub:
4000 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4001 break;
Sebastian Redl22460502009-02-07 00:15:38 +00004002 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00004003 case BinaryOperator::Shr:
4004 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4005 break;
4006 case BinaryOperator::LE:
4007 case BinaryOperator::LT:
4008 case BinaryOperator::GE:
4009 case BinaryOperator::GT:
4010 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
4011 break;
4012 case BinaryOperator::EQ:
4013 case BinaryOperator::NE:
4014 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
4015 break;
4016 case BinaryOperator::And:
4017 case BinaryOperator::Xor:
4018 case BinaryOperator::Or:
4019 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4020 break;
4021 case BinaryOperator::LAnd:
4022 case BinaryOperator::LOr:
4023 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4024 break;
4025 case BinaryOperator::MulAssign:
4026 case BinaryOperator::DivAssign:
4027 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4028 if (!CompTy.isNull())
4029 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4030 break;
4031 case BinaryOperator::RemAssign:
4032 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4033 if (!CompTy.isNull())
4034 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4035 break;
4036 case BinaryOperator::AddAssign:
4037 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
4038 if (!CompTy.isNull())
4039 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4040 break;
4041 case BinaryOperator::SubAssign:
4042 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
4043 if (!CompTy.isNull())
4044 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4045 break;
4046 case BinaryOperator::ShlAssign:
4047 case BinaryOperator::ShrAssign:
4048 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4049 if (!CompTy.isNull())
4050 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4051 break;
4052 case BinaryOperator::AndAssign:
4053 case BinaryOperator::XorAssign:
4054 case BinaryOperator::OrAssign:
4055 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4056 if (!CompTy.isNull())
4057 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
4058 break;
4059 case BinaryOperator::Comma:
4060 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4061 break;
4062 }
4063 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004064 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004065 if (CompTy.isNull())
4066 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4067 else
4068 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004069 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00004070}
4071
Reid Spencer5f016e22007-07-11 17:01:13 +00004072// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004073Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4074 tok::TokenKind Kind,
4075 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004076 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004077 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00004078
Steve Narofff69936d2007-09-16 03:34:24 +00004079 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4080 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004081
Douglas Gregor063daf62009-03-13 18:40:31 +00004082 if (getLangOptions().CPlusPlus &&
4083 (lhs->getType()->isOverloadableType() ||
4084 rhs->getType()->isOverloadableType())) {
4085 // Find all of the overloaded operators visible from this
4086 // point. We perform both an operator-name lookup from the local
4087 // scope and an argument-dependent lookup based on the types of
4088 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004089 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00004090 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4091 if (OverOp != OO_None) {
4092 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4093 Functions);
4094 Expr *Args[2] = { lhs, rhs };
4095 DeclarationName OpName
4096 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4097 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004098 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004099
Douglas Gregor063daf62009-03-13 18:40:31 +00004100 // Build the (potentially-overloaded, potentially-dependent)
4101 // binary operation.
4102 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004103 }
4104
Douglas Gregoreaebc752008-11-06 23:29:22 +00004105 // Build a built-in binary operation.
4106 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00004107}
4108
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004109Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4110 unsigned OpcIn,
4111 ExprArg InputArg) {
4112 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00004113
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004114 // FIXME: Input is modified below, but InputArg is not updated
4115 // appropriately.
4116 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00004117 QualType resultType;
4118 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004119 case UnaryOperator::PostInc:
4120 case UnaryOperator::PostDec:
4121 case UnaryOperator::OffsetOf:
4122 assert(false && "Invalid unary operator");
4123 break;
4124
Reid Spencer5f016e22007-07-11 17:01:13 +00004125 case UnaryOperator::PreInc:
4126 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004127 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4128 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004129 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004130 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00004131 resultType = CheckAddressOfOperand(Input, OpLoc);
4132 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004133 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00004134 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00004135 resultType = CheckIndirectionOperand(Input, OpLoc);
4136 break;
4137 case UnaryOperator::Plus:
4138 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004139 UsualUnaryConversions(Input);
4140 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004141 if (resultType->isDependentType())
4142 break;
Douglas Gregor74253732008-11-19 15:42:04 +00004143 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4144 break;
4145 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4146 resultType->isEnumeralType())
4147 break;
4148 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4149 Opc == UnaryOperator::Plus &&
4150 resultType->isPointerType())
4151 break;
4152
Sebastian Redl0eb23302009-01-19 00:08:26 +00004153 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4154 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004155 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004156 UsualUnaryConversions(Input);
4157 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004158 if (resultType->isDependentType())
4159 break;
Chris Lattner02a65142008-07-25 23:52:49 +00004160 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4161 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4162 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004163 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004164 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00004165 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004166 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4167 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004168 break;
4169 case UnaryOperator::LNot: // logical negation
4170 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004171 DefaultFunctionArrayConversion(Input);
4172 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004173 if (resultType->isDependentType())
4174 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004175 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00004176 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4177 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004178 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00004179 // In C++, it's bool. C++ 5.3.1p8
4180 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004181 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00004182 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00004183 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00004184 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00004185 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004186 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00004187 resultType = Input->getType();
4188 break;
4189 }
4190 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004191 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004192
4193 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004194 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004195}
4196
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004197// Unary Operators. 'Tok' is the token for the operator.
4198Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4199 tok::TokenKind Op, ExprArg input) {
4200 Expr *Input = (Expr*)input.get();
4201 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4202
4203 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4204 // Find all of the overloaded operators visible from this
4205 // point. We perform both an operator-name lookup from the local
4206 // scope and an argument-dependent lookup based on the types of
4207 // the arguments.
4208 FunctionSet Functions;
4209 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4210 if (OverOp != OO_None) {
4211 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4212 Functions);
4213 DeclarationName OpName
4214 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4215 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4216 }
4217
4218 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4219 }
4220
4221 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4222}
4223
Steve Naroff1b273c42007-09-16 14:56:35 +00004224/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00004225Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4226 SourceLocation LabLoc,
4227 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004228 // Look up the record for this label identifier.
Steve Naroffd8eb4562009-03-13 16:03:38 +00004229 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4230 LabelMap[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00004231
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00004232 // If we haven't seen this label yet, create a forward reference. It
4233 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00004234 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00004235 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004236
Reid Spencer5f016e22007-07-11 17:01:13 +00004237 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00004238 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4239 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00004240}
4241
Sebastian Redlf53597f2009-03-15 17:47:39 +00004242Sema::OwningExprResult
4243Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4244 SourceLocation RPLoc) { // "({..})"
4245 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004246 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4247 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4248
Eli Friedmandca2b732009-01-24 23:09:00 +00004249 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4250 if (isFileScope) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00004251 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00004252 }
4253
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004254 // FIXME: there are a variety of strange constraints to enforce here, for
4255 // example, it is not possible to goto into a stmt expression apparently.
4256 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004257
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004258 // FIXME: the last statement in the compount stmt has its value used. We
4259 // should not warn about it being unused.
4260
4261 // If there are sub stmts in the compound stmt, take the type of the last one
4262 // as the type of the stmtexpr.
4263 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004264
Chris Lattner611b2ec2008-07-26 19:51:01 +00004265 if (!Compound->body_empty()) {
4266 Stmt *LastStmt = Compound->body_back();
4267 // If LastStmt is a label, skip down through into the body.
4268 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4269 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004270
Chris Lattner611b2ec2008-07-26 19:51:01 +00004271 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004272 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004273 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004274
Sebastian Redlf53597f2009-03-15 17:47:39 +00004275 substmt.release();
4276 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004277}
Steve Naroffd34e9152007-08-01 22:05:33 +00004278
Sebastian Redlf53597f2009-03-15 17:47:39 +00004279Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4280 SourceLocation BuiltinLoc,
4281 SourceLocation TypeLoc,
4282 TypeTy *argty,
4283 OffsetOfComponent *CompPtr,
4284 unsigned NumComponents,
4285 SourceLocation RPLoc) {
4286 // FIXME: This function leaks all expressions in the offset components on
4287 // error.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004288 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4289 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004290
Sebastian Redl28507842009-02-26 14:39:58 +00004291 bool Dependent = ArgTy->isDependentType();
4292
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004293 // We must have at least one component that refers to the type, and the first
4294 // one is known to be a field designator. Verify that the ArgTy represents
4295 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00004296 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004297 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004298
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00004299 // FIXME: Does the type need to be complete?
4300
Eli Friedman35183ac2009-02-27 06:44:11 +00004301 // Otherwise, create a null pointer as the base, and iteratively process
4302 // the offsetof designators.
4303 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4304 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004305 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00004306 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004307
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004308 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4309 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00004310 // FIXME: This diagnostic isn't actually visible because the location is in
4311 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004312 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004313 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4314 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004315
Sebastian Redl28507842009-02-26 14:39:58 +00004316 if (!Dependent) {
4317 // FIXME: Dependent case loses a lot of information here. And probably
4318 // leaks like a sieve.
4319 for (unsigned i = 0; i != NumComponents; ++i) {
4320 const OffsetOfComponent &OC = CompPtr[i];
4321 if (OC.isBrackets) {
4322 // Offset of an array sub-field. TODO: Should we allow vector elements?
4323 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4324 if (!AT) {
4325 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004326 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4327 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004328 }
4329
4330 // FIXME: C++: Verify that operator[] isn't overloaded.
4331
Eli Friedman35183ac2009-02-27 06:44:11 +00004332 // Promote the array so it looks more like a normal array subscript
4333 // expression.
4334 DefaultFunctionArrayConversion(Res);
4335
Sebastian Redl28507842009-02-26 14:39:58 +00004336 // C99 6.5.2.1p1
4337 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004338 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00004339 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004340 return ExprError(Diag(Idx->getLocStart(),
4341 diag::err_typecheck_subscript)
4342 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00004343
4344 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4345 OC.LocEnd);
4346 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004347 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004348
Sebastian Redl28507842009-02-26 14:39:58 +00004349 const RecordType *RC = Res->getType()->getAsRecordType();
4350 if (!RC) {
4351 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004352 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4353 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004354 }
Chris Lattner704fe352007-08-30 17:59:59 +00004355
Sebastian Redl28507842009-02-26 14:39:58 +00004356 // Get the decl corresponding to this.
4357 RecordDecl *RD = RC->getDecl();
4358 FieldDecl *MemberDecl
4359 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4360 LookupMemberName)
4361 .getAsDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +00004362 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00004363 if (!MemberDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004364 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4365 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00004366
Sebastian Redl28507842009-02-26 14:39:58 +00004367 // FIXME: C++: Verify that MemberDecl isn't a static field.
4368 // FIXME: Verify that MemberDecl isn't a bitfield.
4369 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4370 // matter here.
4371 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004372 MemberDecl->getType().getNonReferenceType());
Sebastian Redl28507842009-02-26 14:39:58 +00004373 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004374 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004375
Sebastian Redlf53597f2009-03-15 17:47:39 +00004376 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4377 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004378}
4379
4380
Sebastian Redlf53597f2009-03-15 17:47:39 +00004381Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4382 TypeTy *arg1,TypeTy *arg2,
4383 SourceLocation RPLoc) {
Steve Naroffd34e9152007-08-01 22:05:33 +00004384 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4385 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004386
Steve Naroffd34e9152007-08-01 22:05:33 +00004387 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004388
Sebastian Redlf53597f2009-03-15 17:47:39 +00004389 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4390 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00004391}
4392
Sebastian Redlf53597f2009-03-15 17:47:39 +00004393Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4394 ExprArg cond,
4395 ExprArg expr1, ExprArg expr2,
4396 SourceLocation RPLoc) {
4397 Expr *CondExpr = static_cast<Expr*>(cond.get());
4398 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4399 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004400
Steve Naroffd04fdd52007-08-03 21:21:27 +00004401 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4402
Sebastian Redl28507842009-02-26 14:39:58 +00004403 QualType resType;
4404 if (CondExpr->isValueDependent()) {
4405 resType = Context.DependentTy;
4406 } else {
4407 // The conditional expression is required to be a constant expression.
4408 llvm::APSInt condEval(32);
4409 SourceLocation ExpLoc;
4410 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00004411 return ExprError(Diag(ExpLoc,
4412 diag::err_typecheck_choose_expr_requires_constant)
4413 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00004414
Sebastian Redl28507842009-02-26 14:39:58 +00004415 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4416 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4417 }
4418
Sebastian Redlf53597f2009-03-15 17:47:39 +00004419 cond.release(); expr1.release(); expr2.release();
4420 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4421 resType, RPLoc));
Steve Naroffd04fdd52007-08-03 21:21:27 +00004422}
4423
Steve Naroff4eb206b2008-09-03 18:15:37 +00004424//===----------------------------------------------------------------------===//
4425// Clang Extensions.
4426//===----------------------------------------------------------------------===//
4427
4428/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004429void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004430 // Analyze block parameters.
4431 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004432
Steve Naroff4eb206b2008-09-03 18:15:37 +00004433 // Add BSI to CurBlock.
4434 BSI->PrevBlockInfo = CurBlock;
4435 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004436
Steve Naroff4eb206b2008-09-03 18:15:37 +00004437 BSI->ReturnType = 0;
4438 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00004439 BSI->hasBlockDeclRefExprs = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004440
Steve Naroff090276f2008-10-10 01:28:17 +00004441 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004442 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004443}
4444
Mike Stump98eb8a72009-02-04 22:31:32 +00004445void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4446 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4447
4448 if (ParamInfo.getNumTypeObjects() == 0
4449 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4450 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4451
4452 // The type is entirely optional as well, if none, use DependentTy.
4453 if (T.isNull())
4454 T = Context.DependentTy;
4455
4456 // The parameter list is optional, if there was none, assume ().
4457 if (!T->isFunctionType())
4458 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4459
4460 CurBlock->hasPrototype = true;
4461 CurBlock->isVariadic = false;
4462 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4463 .getTypePtr();
4464
4465 if (!RetTy->isDependentType())
4466 CurBlock->ReturnType = RetTy;
4467 return;
4468 }
4469
Steve Naroff4eb206b2008-09-03 18:15:37 +00004470 // Analyze arguments to block.
4471 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4472 "Not a function declarator!");
4473 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004474
Steve Naroff090276f2008-10-10 01:28:17 +00004475 CurBlock->hasPrototype = FTI.hasPrototype;
4476 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004477
Steve Naroff4eb206b2008-09-03 18:15:37 +00004478 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4479 // no arguments, not a function that takes a single void argument.
4480 if (FTI.hasPrototype &&
4481 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4482 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4483 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4484 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004485 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004486 } else if (FTI.hasPrototype) {
4487 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004488 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4489 CurBlock->isVariadic = FTI.isVariadic;
Mike Stump98eb8a72009-02-04 22:31:32 +00004490 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4491
4492 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4493 .getTypePtr();
4494
4495 if (!RetTy->isDependentType())
4496 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004497 }
Steve Naroffe78b8092009-03-13 16:56:44 +00004498 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4499 CurBlock->Params.size());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004500
Steve Naroff090276f2008-10-10 01:28:17 +00004501 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4502 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4503 // If this has an identifier, add it to the scope stack.
4504 if ((*AI)->getIdentifier())
4505 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004506}
4507
4508/// ActOnBlockError - If there is an error parsing a block, this callback
4509/// is invoked to pop the information about the block from the action impl.
4510void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4511 // Ensure that CurBlock is deleted.
4512 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004513
Steve Naroff4eb206b2008-09-03 18:15:37 +00004514 // Pop off CurBlock, handle nested blocks.
4515 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004516
Steve Naroff4eb206b2008-09-03 18:15:37 +00004517 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregor4a471aa2009-03-11 23:54:15 +00004518
Steve Naroff4eb206b2008-09-03 18:15:37 +00004519}
4520
4521/// ActOnBlockStmtExpr - This is called when the body of a block statement
4522/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00004523Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4524 StmtArg body, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004525 // Ensure that CurBlock is deleted.
4526 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004527
Steve Naroff090276f2008-10-10 01:28:17 +00004528 PopDeclContext();
4529
Steve Naroff4eb206b2008-09-03 18:15:37 +00004530 // Pop off CurBlock, handle nested blocks.
4531 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004532
Steve Naroff4eb206b2008-09-03 18:15:37 +00004533 QualType RetTy = Context.VoidTy;
4534 if (BSI->ReturnType)
4535 RetTy = QualType(BSI->ReturnType, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004536
Steve Naroff4eb206b2008-09-03 18:15:37 +00004537 llvm::SmallVector<QualType, 8> ArgTypes;
4538 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4539 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004540
Steve Naroff4eb206b2008-09-03 18:15:37 +00004541 QualType BlockTy;
4542 if (!BSI->hasPrototype)
Douglas Gregor72564e72009-02-26 23:50:07 +00004543 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004544 else
4545 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004546 BSI->isVariadic, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004547
Steve Naroff4eb206b2008-09-03 18:15:37 +00004548 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004549
Sebastian Redlf53597f2009-03-15 17:47:39 +00004550 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4551 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4552 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00004553}
4554
Sebastian Redlf53597f2009-03-15 17:47:39 +00004555Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4556 ExprArg expr, TypeTy *type,
4557 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004558 QualType T = QualType::getFromOpaquePtr(type);
4559
4560 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004561
4562 // Get the va_list type
4563 QualType VaListType = Context.getBuiltinVaListType();
4564 // Deal with implicit array decay; for example, on x86-64,
4565 // va_list is an array, but it's supposed to decay to
4566 // a pointer for va_arg.
4567 if (VaListType->isArrayType())
4568 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004569 // Make sure the input expression also decays appropriately.
Sebastian Redlf53597f2009-03-15 17:47:39 +00004570 Expr *E = static_cast<Expr*>(expr.get());
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004571 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004572
4573 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004574 return ExprError(Diag(E->getLocStart(),
4575 diag::err_first_argument_to_va_arg_not_of_type_va_list)
4576 << E->getType() << E->getSourceRange());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004577
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004578 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004579
Sebastian Redlf53597f2009-03-15 17:47:39 +00004580 expr.release();
4581 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4582 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004583}
4584
Sebastian Redlf53597f2009-03-15 17:47:39 +00004585Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004586 // The type of __null will be int or long, depending on the size of
4587 // pointers on the target.
4588 QualType Ty;
4589 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4590 Ty = Context.IntTy;
4591 else
4592 Ty = Context.LongTy;
4593
Sebastian Redlf53597f2009-03-15 17:47:39 +00004594 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004595}
4596
Chris Lattner5cf216b2008-01-04 18:04:52 +00004597bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4598 SourceLocation Loc,
4599 QualType DstType, QualType SrcType,
4600 Expr *SrcExpr, const char *Flavor) {
4601 // Decode the result (notice that AST's are still created for extensions).
4602 bool isInvalid = false;
4603 unsigned DiagKind;
4604 switch (ConvTy) {
4605 default: assert(0 && "Unknown conversion type");
4606 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004607 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004608 DiagKind = diag::ext_typecheck_convert_pointer_int;
4609 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004610 case IntToPointer:
4611 DiagKind = diag::ext_typecheck_convert_int_pointer;
4612 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004613 case IncompatiblePointer:
4614 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4615 break;
4616 case FunctionVoidPointer:
4617 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4618 break;
4619 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004620 // If the qualifiers lost were because we were applying the
4621 // (deprecated) C++ conversion from a string literal to a char*
4622 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4623 // Ideally, this check would be performed in
4624 // CheckPointerTypesForAssignment. However, that would require a
4625 // bit of refactoring (so that the second argument is an
4626 // expression, rather than a type), which should be done as part
4627 // of a larger effort to fix CheckPointerTypesForAssignment for
4628 // C++ semantics.
4629 if (getLangOptions().CPlusPlus &&
4630 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4631 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004632 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4633 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004634 case IntToBlockPointer:
4635 DiagKind = diag::err_int_to_block_pointer;
4636 break;
4637 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004638 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004639 break;
Steve Naroff39579072008-10-14 22:18:38 +00004640 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00004641 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00004642 // it can give a more specific diagnostic.
4643 DiagKind = diag::warn_incompatible_qualified_id;
4644 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004645 case IncompatibleVectors:
4646 DiagKind = diag::warn_incompatible_vectors;
4647 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004648 case Incompatible:
4649 DiagKind = diag::err_typecheck_convert_incompatible;
4650 isInvalid = true;
4651 break;
4652 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004653
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004654 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4655 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004656 return isInvalid;
4657}
Anders Carlssone21555e2008-11-30 19:50:32 +00004658
4659bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4660{
4661 Expr::EvalResult EvalResult;
4662
Mike Stumpeed9cac2009-02-19 03:04:26 +00004663 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00004664 EvalResult.HasSideEffects) {
4665 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4666
4667 if (EvalResult.Diag) {
4668 // We only show the note if it's not the usual "invalid subexpression"
4669 // or if it's actually in a subexpression.
4670 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4671 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4672 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4673 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004674
Anders Carlssone21555e2008-11-30 19:50:32 +00004675 return true;
4676 }
4677
4678 if (EvalResult.Diag) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004679 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssone21555e2008-11-30 19:50:32 +00004680 E->getSourceRange();
4681
4682 // Print the reason it's not a constant.
4683 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4684 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4685 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004686
Anders Carlssone21555e2008-11-30 19:50:32 +00004687 if (Result)
4688 *Result = EvalResult.Val.getInt();
4689 return false;
4690}