blob: cec94cfdf064792630d613bd163c30bbffd408b7 [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) {
Steve Naroff6ece14c2009-01-21 00:14:39 +0000442 if (SS && !SS->isEmpty())
443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stumpeed9cac2009-02-19 03:04:26 +0000444 ValueDependent,
445 SS->getRange().getBegin());
Steve Naroff6ece14c2009-01-21 00:14:39 +0000446 else
447 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000448}
449
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
451/// variable corresponding to the anonymous union or struct whose type
452/// is Record.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000453static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000454 assert(Record->isAnonymousStructOrUnion() &&
455 "Record must be an anonymous struct or union!");
456
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000457 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000458 // be an O(1) operation rather than a slow walk through DeclContext's
459 // vector (which itself will be eliminated). DeclGroups might make
460 // this even better.
461 DeclContext *Ctx = Record->getDeclContext();
462 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
463 DEnd = Ctx->decls_end();
464 D != DEnd; ++D) {
465 if (*D == Record) {
466 // The object for the anonymous struct/union directly
467 // follows its type in the list of declarations.
468 ++D;
469 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000470 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000471 return *D;
472 }
473 }
474
475 assert(false && "Missing object for anonymous record");
476 return 0;
477}
478
Sebastian Redlcd965b92009-01-18 18:53:16 +0000479Sema::OwningExprResult
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000480Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
481 FieldDecl *Field,
482 Expr *BaseObjectExpr,
483 SourceLocation OpLoc) {
484 assert(Field->getDeclContext()->isRecord() &&
485 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
486 && "Field must be stored inside an anonymous struct or union");
487
488 // Construct the sequence of field member references
489 // we'll have to perform to get to the field in the anonymous
490 // union/struct. The list of members is built from the field
491 // outward, so traverse it backwards to go from an object in
492 // the current context to the field we found.
493 llvm::SmallVector<FieldDecl *, 4> AnonFields;
494 AnonFields.push_back(Field);
495 VarDecl *BaseObject = 0;
496 DeclContext *Ctx = Field->getDeclContext();
497 do {
498 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000499 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000500 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
501 AnonFields.push_back(AnonField);
502 else {
503 BaseObject = cast<VarDecl>(AnonObject);
504 break;
505 }
506 Ctx = Ctx->getParent();
507 } while (Ctx->isRecord() &&
508 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
509
510 // Build the expression that refers to the base object, from
511 // which we will build a sequence of member references to each
512 // of the anonymous union objects and, eventually, the field we
513 // found via name lookup.
514 bool BaseObjectIsPointer = false;
515 unsigned ExtraQuals = 0;
516 if (BaseObject) {
517 // BaseObject is an anonymous struct/union variable (and is,
518 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000519 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000520 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000521 SourceLocation());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000522 ExtraQuals
523 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
524 } else if (BaseObjectExpr) {
525 // The caller provided the base object expression. Determine
526 // whether its a pointer and whether it adds any qualifiers to the
527 // anonymous struct/union fields we're looking into.
528 QualType ObjectType = BaseObjectExpr->getType();
529 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
530 BaseObjectIsPointer = true;
531 ObjectType = ObjectPtr->getPointeeType();
532 }
533 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
534 } else {
535 // We've found a member of an anonymous struct/union that is
536 // inside a non-anonymous struct/union, so in a well-formed
537 // program our base object expression is "this".
538 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
539 if (!MD->isStatic()) {
540 QualType AnonFieldType
541 = Context.getTagDeclType(
542 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
543 QualType ThisType = Context.getTagDeclType(MD->getParent());
544 if ((Context.getCanonicalType(AnonFieldType)
545 == Context.getCanonicalType(ThisType)) ||
546 IsDerivedFrom(ThisType, AnonFieldType)) {
547 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000548 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000549 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000550 BaseObjectIsPointer = true;
551 }
552 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000553 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
554 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000555 }
556 ExtraQuals = MD->getTypeQualifiers();
557 }
558
559 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000560 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
561 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000562 }
563
564 // Build the implicit member references to the field of the
565 // anonymous struct/union.
566 Expr *Result = BaseObjectExpr;
567 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
568 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
569 FI != FIEnd; ++FI) {
570 QualType MemberType = (*FI)->getType();
571 if (!(*FI)->isMutable()) {
572 unsigned combinedQualifiers
573 = MemberType.getCVRQualifiers() | ExtraQuals;
574 MemberType = MemberType.getQualifiedType(combinedQualifiers);
575 }
Steve Naroff6ece14c2009-01-21 00:14:39 +0000576 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
577 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000578 BaseObjectIsPointer = false;
579 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 }
581
Sebastian Redlcd965b92009-01-18 18:53:16 +0000582 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000583}
584
Douglas Gregor10c42622008-11-18 15:03:34 +0000585/// ActOnDeclarationNameExpr - The parser has read some kind of name
586/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
587/// performs lookup on that name and returns an expression that refers
588/// to that name. This routine isn't directly called from the parser,
589/// because the parser doesn't know about DeclarationName. Rather,
590/// this routine is called by ActOnIdentifierExpr,
591/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
592/// which form the DeclarationName from the corresponding syntactic
593/// forms.
594///
595/// HasTrailingLParen indicates whether this identifier is used in a
596/// function call context. LookupCtx is only used for a C++
597/// qualified-id (foo::bar) to indicate the class or namespace that
598/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000599///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000600/// isAddressOfOperand means that this expression is the direct operand
601/// of an address-of operator. This matters because this is the only
602/// situation where a qualified name referencing a non-static member may
603/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000604Sema::OwningExprResult
605Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
606 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +0000607 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000608 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000609 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000610 if (SS && SS->isInvalid())
611 return ExprError();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000612 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
613 false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000614
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000615 NamedDecl *D = 0;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000616 if (Lookup.isAmbiguous()) {
617 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
618 SS && SS->isSet() ? SS->getRange()
619 : SourceRange());
620 return ExprError();
621 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000622 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000623
Chris Lattner8a934232008-03-31 00:36:02 +0000624 // If this reference is in an Objective-C method, then ivar lookup happens as
625 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000626 IdentifierInfo *II = Name.getAsIdentifierInfo();
627 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000628 // There are two cases to handle here. 1) scoped lookup could have failed,
629 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000630 // found a decl, but that decl is outside the current instance method (i.e.
631 // a global variable). In these two cases, we do a lookup for an ivar with
632 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000633 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000634 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000635 ObjCInterfaceDecl *ClassDeclared;
636 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000637 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000638 if (DiagnoseUseOfDecl(IV, Loc))
639 return ExprError();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000640 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
641 // If a class method attemps to use a free standing ivar, this is
642 // an error.
643 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
644 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
645 << IV->getDeclName());
646 // If a class method uses a global variable, even if an ivar with
647 // same name exists, use the global.
648 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000649 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
650 ClassDeclared != IFace)
651 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000652 // FIXME: This should use a new expr for a direct reference, don't turn
653 // this into Self->ivar, just return a BareIVarExpr or something.
654 IdentifierInfo &II = Context.Idents.get("self");
655 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
656 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
657 Loc, static_cast<Expr*>(SelfExpr.release()),
658 true, true);
659 Context.setFieldDecl(IFace, IV, MRef);
660 return Owned(MRef);
661 }
Chris Lattner8a934232008-03-31 00:36:02 +0000662 }
663 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000664 else if (getCurMethodDecl()->isInstanceMethod()) {
665 // We should warn if a local variable hides an ivar.
666 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000667 ObjCInterfaceDecl *ClassDeclared;
668 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
669 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
670 IFace == ClassDeclared)
671 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
672 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000673 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000674 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000675 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000676 QualType T;
677
678 if (getCurMethodDecl()->isInstanceMethod())
679 T = Context.getPointerType(Context.getObjCInterfaceType(
680 getCurMethodDecl()->getClassInterface()));
681 else
682 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000683 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000684 }
Chris Lattner8a934232008-03-31 00:36:02 +0000685 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000686
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000687 // Determine whether this name might be a candidate for
688 // argument-dependent lookup.
689 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
690 HasTrailingLParen;
691
692 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000693 // We've seen something of the form
694 //
695 // identifier(
696 //
697 // and we did not find any entity by the name
698 // "identifier". However, this identifier is still subject to
699 // argument-dependent lookup, so keep track of the name.
700 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
701 Context.OverloadTy,
702 Loc));
703 }
704
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 if (D == 0) {
706 // Otherwise, this could be an implicitly declared function reference (legal
707 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000708 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000709 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000710 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 else {
712 // If this name wasn't predeclared and if this is not a function call,
713 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000714 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000715 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
716 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000717 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
718 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000719 return ExprError(Diag(Loc, diag::err_undeclared_use)
720 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000721 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000722 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 }
724 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000725
Sebastian Redlebc07d52009-02-03 20:19:35 +0000726 // If this is an expression of the form &Class::member, don't build an
727 // implicit member ref, because we want a pointer to the member in general,
728 // not any specific instance's member.
729 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000730 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000731 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000732 QualType DType;
733 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
734 DType = FD->getType().getNonReferenceType();
735 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
736 DType = Method->getType();
737 } else if (isa<OverloadedFunctionDecl>(D)) {
738 DType = Context.OverloadTy;
739 }
740 // Could be an inner type. That's diagnosed below, so ignore it here.
741 if (!DType.isNull()) {
742 // The pointer is type- and value-dependent if it points into something
743 // dependent.
744 bool Dependent = false;
745 for (; DC; DC = DC->getParent()) {
746 // FIXME: could stop early at namespace scope.
747 if (DC->isRecord()) {
748 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
749 if (Context.getTypeDeclType(Record)->isDependentType()) {
750 Dependent = true;
751 break;
752 }
753 }
754 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000755 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redlebc07d52009-02-03 20:19:35 +0000756 }
757 }
758 }
759
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000760 // We may have found a field within an anonymous union or struct
761 // (C++ [class.union]).
762 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
763 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
764 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000765
Douglas Gregor88a35142008-12-22 05:46:06 +0000766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
767 if (!MD->isStatic()) {
768 // C++ [class.mfct.nonstatic]p2:
769 // [...] if name lookup (3.4.1) resolves the name in the
770 // id-expression to a nonstatic nontype member of class X or of
771 // a base class of X, the id-expression is transformed into a
772 // class member access expression (5.2.5) using (*this) (9.3.2)
773 // as the postfix-expression to the left of the '.' operator.
774 DeclContext *Ctx = 0;
775 QualType MemberType;
776 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
777 Ctx = FD->getDeclContext();
778 MemberType = FD->getType();
779
780 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
781 MemberType = RefType->getPointeeType();
782 else if (!FD->isMutable()) {
783 unsigned combinedQualifiers
784 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
785 MemberType = MemberType.getQualifiedType(combinedQualifiers);
786 }
787 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
788 if (!Method->isStatic()) {
789 Ctx = Method->getParent();
790 MemberType = Method->getType();
791 }
792 } else if (OverloadedFunctionDecl *Ovl
793 = dyn_cast<OverloadedFunctionDecl>(D)) {
794 for (OverloadedFunctionDecl::function_iterator
795 Func = Ovl->function_begin(),
796 FuncEnd = Ovl->function_end();
797 Func != FuncEnd; ++Func) {
798 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
799 if (!DMethod->isStatic()) {
800 Ctx = Ovl->getDeclContext();
801 MemberType = Context.OverloadTy;
802 break;
803 }
804 }
805 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000806
807 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000808 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
809 QualType ThisType = Context.getTagDeclType(MD->getParent());
810 if ((Context.getCanonicalType(CtxType)
811 == Context.getCanonicalType(ThisType)) ||
812 IsDerivedFrom(ThisType, CtxType)) {
813 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000814 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000815 MD->getThisType(Context));
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000816 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stumpeed9cac2009-02-19 03:04:26 +0000817 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000818 }
819 }
820 }
821 }
822
Douglas Gregor44b43212008-12-11 16:49:14 +0000823 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000824 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
825 if (MD->isStatic())
826 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000827 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
828 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000829 }
830
Douglas Gregor88a35142008-12-22 05:46:06 +0000831 // Any other ways we could have found the field in a well-formed
832 // program would have been turned into implicit member expressions
833 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000834 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
835 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000836 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000837
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000839 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000840 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000841 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000842 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000843 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
Steve Naroffdd972f22008-09-05 22:11:13 +0000845 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000846 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000847 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
848 false, false, SS));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000849 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
850 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
851 false, false, SS));
Steve Naroffdd972f22008-09-05 22:11:13 +0000852 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000853
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000854 // Check whether this declaration can be used. Note that we suppress
855 // this check when we're going to perform argument-dependent lookup
856 // on this function name, because this might not be the function
857 // that overload resolution actually selects.
858 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
859 return ExprError();
860
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000861 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000862 // Warn about constructs like:
863 // if (void *X = foo()) { ... } else { X }.
864 // In the else block, the pointer is always false.
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000865 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
866 Scope *CheckS = S;
867 while (CheckS) {
868 if (CheckS->isWithinElse() &&
869 CheckS->getControlParent()->isDeclScope(Var)) {
870 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000871 ExprError(Diag(Loc, diag::warn_value_always_false)
872 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000873 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000874 ExprError(Diag(Loc, diag::warn_value_always_zero)
875 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000876 break;
877 }
878
879 // Move up one more control parent to check again.
880 CheckS = CheckS->getControlParent();
881 if (CheckS)
882 CheckS = CheckS->getParent();
883 }
884 }
Douglas Gregor2224f842009-02-25 16:33:18 +0000885 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
886 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
887 // C99 DR 316 says that, if a function type comes from a
888 // function definition (without a prototype), that type is only
889 // used for checking compatibility. Therefore, when referencing
890 // the function, we pretend that we don't have the full function
891 // type.
892 QualType T = Func->getType();
893 QualType NoProtoType = T;
Douglas Gregor72564e72009-02-26 23:50:07 +0000894 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
895 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor2224f842009-02-25 16:33:18 +0000896 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
897 }
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000898 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000899
900 // Only create DeclRefExpr's for valid Decl's.
901 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000902 return ExprError();
903
Chris Lattner639e2d32008-10-20 05:16:36 +0000904 // If the identifier reference is inside a block, and it refers to a value
905 // that is outside the block, create a BlockDeclRefExpr instead of a
906 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
907 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000908 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000909 // We do not do this for things like enum constants, global variables, etc,
910 // as they do not get snapshotted.
911 //
912 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000913 // Blocks that have these can't be constant.
914 CurBlock->hasBlockDeclRefExprs = true;
915
Steve Naroff090276f2008-10-10 01:28:17 +0000916 // The BlocksAttr indicates the variable is bound by-reference.
917 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000918 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000919 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000920
Steve Naroff090276f2008-10-10 01:28:17 +0000921 // Variable will be bound by-copy, make it const within the closure.
922 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000923 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000924 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000925 }
926 // If this reference is not in a block or if the referenced variable is
927 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000928
Douglas Gregor898574e2008-12-05 23:32:09 +0000929 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000930 bool ValueDependent = false;
931 if (getLangOptions().CPlusPlus) {
932 // C++ [temp.dep.expr]p3:
933 // An id-expression is type-dependent if it contains:
934 // - an identifier that was declared with a dependent type,
935 if (VD->getType()->isDependentType())
936 TypeDependent = true;
937 // - FIXME: a template-id that is dependent,
938 // - a conversion-function-id that specifies a dependent type,
939 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
940 Name.getCXXNameType()->isDependentType())
941 TypeDependent = true;
942 // - a nested-name-specifier that contains a class-name that
943 // names a dependent type.
944 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000945 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +0000946 DC; DC = DC->getParent()) {
947 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000948 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000949 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
950 if (Context.getTypeDeclType(Record)->isDependentType()) {
951 TypeDependent = true;
952 break;
953 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000954 }
955 }
956 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000957
Douglas Gregor83f96f62008-12-10 20:57:37 +0000958 // C++ [temp.dep.constexpr]p2:
959 //
960 // An identifier is value-dependent if it is:
961 // - a name declared with a dependent type,
962 if (TypeDependent)
963 ValueDependent = true;
964 // - the name of a non-type template parameter,
965 else if (isa<NonTypeTemplateParmDecl>(VD))
966 ValueDependent = true;
967 // - a constant with integral or enumeration type and is
968 // initialized with an expression that is value-dependent
969 // (FIXME!).
970 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000971
Sebastian Redlcd965b92009-01-18 18:53:16 +0000972 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
973 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000974}
975
Sebastian Redlcd965b92009-01-18 18:53:16 +0000976Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
977 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000978 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000979
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000981 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000982 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
983 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
984 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000986
Chris Lattnerfa28b302008-01-12 08:14:25 +0000987 // Pre-defined identifiers are of type char[x], where x is the length of the
988 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000989 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000990 if (FunctionDecl *FD = getCurFunctionDecl())
991 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000992 else if (ObjCMethodDecl *MD = getCurMethodDecl())
993 Length = MD->getSynthesizedMethodSize();
994 else {
995 Diag(Loc, diag::ext_predef_outside_function);
996 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
997 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
998 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000999
1000
Chris Lattner8f978d52008-01-12 19:32:28 +00001001 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +00001002 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +00001003 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +00001004 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001005}
1006
Sebastian Redlcd965b92009-01-18 18:53:16 +00001007Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 llvm::SmallString<16> CharBuffer;
1009 CharBuffer.resize(Tok.getLength());
1010 const char *ThisTokBegin = &CharBuffer[0];
1011 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001012
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1014 Tok.getLocation(), PP);
1015 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001016 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001017
1018 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1019
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001020 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1021 Literal.isWide(),
1022 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001023}
1024
Sebastian Redlcd965b92009-01-18 18:53:16 +00001025Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1026 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1028 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001029 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001030 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001031 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001032 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 }
Ted Kremenek28396602009-01-13 23:19:12 +00001034
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001036 // Add padding so that NumericLiteralParser can overread by one character.
1037 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001039
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 // Get the spelling of the token, which eliminates trigraphs, etc.
1041 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001042
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1044 Tok.getLocation(), PP);
1045 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001046 return ExprError();
1047
Chris Lattner5d661452007-08-26 03:42:43 +00001048 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001049
Chris Lattner5d661452007-08-26 03:42:43 +00001050 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001051 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001052 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001053 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001054 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001055 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001056 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001057 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001058
1059 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1060
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001061 // isExact will be set by GetFloatValue().
1062 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001063 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1064 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001065
Chris Lattner5d661452007-08-26 03:42:43 +00001066 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001067 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001068 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001069 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001070
Neil Boothb9449512007-08-29 22:00:19 +00001071 // long long is a C99 feature.
1072 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001073 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001074 Diag(Tok.getLocation(), diag::ext_longlong);
1075
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001077 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001078
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 if (Literal.GetIntegerValue(ResultVal)) {
1080 // If this value didn't fit into uintmax_t, warn and force to ull.
1081 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001082 Ty = Context.UnsignedLongLongTy;
1083 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001084 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 } else {
1086 // If this value fits into a ULL, try to figure out what else it fits into
1087 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001088
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1090 // be an unsigned int.
1091 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1092
1093 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001094 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001095 if (!Literal.isLong && !Literal.isLongLong) {
1096 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001097 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001098
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 // Does it fit in a unsigned int?
1100 if (ResultVal.isIntN(IntSize)) {
1101 // Does it fit in a signed int?
1102 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001103 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001105 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001106 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001109
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001111 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001112 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001113
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 // Does it fit in a unsigned long?
1115 if (ResultVal.isIntN(LongSize)) {
1116 // Does it fit in a signed long?
1117 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001118 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001120 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001121 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001123 }
1124
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001126 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001127 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // Does it fit in a unsigned long long?
1130 if (ResultVal.isIntN(LongLongSize)) {
1131 // Does it fit in a signed long long?
1132 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001133 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001135 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001136 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 }
1138 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 // If we still couldn't decide a type, we probably have something that
1141 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001142 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001144 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001145 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001147
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001148 if (ResultVal.getBitWidth() != Width)
1149 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001151 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001153
Chris Lattner5d661452007-08-26 03:42:43 +00001154 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1155 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001156 Res = new (Context) ImaginaryLiteral(Res,
1157 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001158
1159 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001160}
1161
Sebastian Redlcd965b92009-01-18 18:53:16 +00001162Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1163 SourceLocation R, ExprArg Val) {
1164 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001165 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001166 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001167}
1168
1169/// The UsualUnaryConversions() function is *not* called by this routine.
1170/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001171bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001172 SourceLocation OpLoc,
1173 const SourceRange &ExprRange,
1174 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001175 if (exprType->isDependentType())
1176 return false;
1177
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001179 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001181 if (isSizeof)
1182 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1183 return false;
1184 }
1185
1186 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001187 Diag(OpLoc, diag::ext_sizeof_void_type)
1188 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001189 return false;
1190 }
Sebastian Redl05189992008-11-11 17:56:53 +00001191
Douglas Gregor86447ec2009-03-09 16:13:40 +00001192 return RequireCompleteType(OpLoc, exprType,
Chris Lattner01072922009-01-24 19:46:37 +00001193 isSizeof ? diag::err_sizeof_incomplete_type :
1194 diag::err_alignof_incomplete_type,
1195 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001196}
1197
Chris Lattner31e21e02009-01-24 20:17:12 +00001198bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1199 const SourceRange &ExprRange) {
1200 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001201
Chris Lattner31e21e02009-01-24 20:17:12 +00001202 // alignof decl is always ok.
1203 if (isa<DeclRefExpr>(E))
1204 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001205
1206 // Cannot know anything else if the expression is dependent.
1207 if (E->isTypeDependent())
1208 return false;
1209
Chris Lattner31e21e02009-01-24 20:17:12 +00001210 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1211 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1212 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001213 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001214 return true;
1215 }
1216 // Other fields are ok.
1217 return false;
1218 }
1219 }
1220 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1221}
1222
Douglas Gregorba498172009-03-13 21:01:28 +00001223/// \brief Build a sizeof or alignof expression given a type operand.
1224Action::OwningExprResult
1225Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1226 bool isSizeOf, SourceRange R) {
1227 if (T.isNull())
1228 return ExprError();
1229
1230 if (!T->isDependentType() &&
1231 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1232 return ExprError();
1233
1234 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1235 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1236 Context.getSizeType(), OpLoc,
1237 R.getEnd()));
1238}
1239
1240/// \brief Build a sizeof or alignof expression given an expression
1241/// operand.
1242Action::OwningExprResult
1243Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1244 bool isSizeOf, SourceRange R) {
1245 // Verify that the operand is valid.
1246 bool isInvalid = false;
1247 if (E->isTypeDependent()) {
1248 // Delay type-checking for type-dependent expressions.
1249 } else if (!isSizeOf) {
1250 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1251 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1252 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1253 isInvalid = true;
1254 } else {
1255 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1256 }
1257
1258 if (isInvalid)
1259 return ExprError();
1260
1261 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1262 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1263 Context.getSizeType(), OpLoc,
1264 R.getEnd()));
1265}
1266
Sebastian Redl05189992008-11-11 17:56:53 +00001267/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1268/// the same for @c alignof and @c __alignof
1269/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001270Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001271Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1272 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001274 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001275
Sebastian Redl05189992008-11-11 17:56:53 +00001276 if (isType) {
Douglas Gregorba498172009-03-13 21:01:28 +00001277 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1278 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1279 }
Sebastian Redl05189992008-11-11 17:56:53 +00001280
Douglas Gregorba498172009-03-13 21:01:28 +00001281 // Get the end location.
1282 Expr *ArgEx = (Expr *)TyOrEx;
1283 Action::OwningExprResult Result
1284 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1285
1286 if (Result.isInvalid())
1287 DeleteExpr(ArgEx);
1288
1289 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001290}
1291
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001292QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001293 if (V->isTypeDependent())
1294 return Context.DependentTy;
1295
Chris Lattnerdbb36972007-08-24 21:16:53 +00001296 DefaultFunctionArrayConversion(V);
1297
Chris Lattnercc26ed72007-08-26 05:39:26 +00001298 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001299 if (const ComplexType *CT = V->getType()->getAsComplexType())
1300 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001301
1302 // Otherwise they pass through real integer and floating point types here.
1303 if (V->getType()->isArithmeticType())
1304 return V->getType();
1305
1306 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001307 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1308 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001309 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001310}
1311
1312
Reid Spencer5f016e22007-07-11 17:01:13 +00001313
Sebastian Redl0eb23302009-01-19 00:08:26 +00001314Action::OwningExprResult
1315Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1316 tok::TokenKind Kind, ExprArg Input) {
1317 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001318
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 UnaryOperator::Opcode Opc;
1320 switch (Kind) {
1321 default: assert(0 && "Unknown unary op!");
1322 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1323 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1324 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001325
Douglas Gregor74253732008-11-19 15:42:04 +00001326 if (getLangOptions().CPlusPlus &&
1327 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1328 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001329 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001330 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1331
1332 // C++ [over.inc]p1:
1333 //
1334 // [...] If the function is a member function with one
1335 // parameter (which shall be of type int) or a non-member
1336 // function with two parameters (the second of which shall be
1337 // of type int), it defines the postfix increment operator ++
1338 // for objects of that type. When the postfix increment is
1339 // called as a result of using the ++ operator, the int
1340 // argument will have value zero.
1341 Expr *Args[2] = {
1342 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001343 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1344 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001345 };
1346
1347 // Build the candidate set for overloading
1348 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001349 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001350
1351 // Perform overload resolution.
1352 OverloadCandidateSet::iterator Best;
1353 switch (BestViableFunction(CandidateSet, Best)) {
1354 case OR_Success: {
1355 // We found a built-in operator or an overloaded operator.
1356 FunctionDecl *FnDecl = Best->Function;
1357
1358 if (FnDecl) {
1359 // We matched an overloaded operator. Build a call to that
1360 // operator.
1361
1362 // Convert the arguments.
1363 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1364 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001365 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001366 } else {
1367 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001368 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001369 FnDecl->getParamDecl(0)->getType(),
1370 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001371 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001372 }
1373
1374 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001375 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001376 = FnDecl->getType()->getAsFunctionType()->getResultType();
1377 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001378
Douglas Gregor74253732008-11-19 15:42:04 +00001379 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001380 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001381 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001382 UsualUnaryConversions(FnExpr);
1383
Sebastian Redl0eb23302009-01-19 00:08:26 +00001384 Input.release();
Douglas Gregor063daf62009-03-13 18:40:31 +00001385 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1386 Args, 2, ResultTy,
1387 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001388 } else {
1389 // We matched a built-in operator. Convert the arguments, then
1390 // break out so that we will build the appropriate built-in
1391 // operator node.
1392 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1393 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001394 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001395
1396 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001397 }
Douglas Gregor74253732008-11-19 15:42:04 +00001398 }
1399
1400 case OR_No_Viable_Function:
1401 // No viable function; fall through to handling this as a
1402 // built-in operator, which will produce an error message for us.
1403 break;
1404
1405 case OR_Ambiguous:
1406 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1407 << UnaryOperator::getOpcodeStr(Opc)
1408 << Arg->getSourceRange();
1409 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001410 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001411
1412 case OR_Deleted:
1413 Diag(OpLoc, diag::err_ovl_deleted_oper)
1414 << Best->Function->isDeleted()
1415 << UnaryOperator::getOpcodeStr(Opc)
1416 << Arg->getSourceRange();
1417 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1418 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001419 }
1420
1421 // Either we found no viable overloaded operator or we matched a
1422 // built-in operator. In either case, fall through to trying to
1423 // build a built-in operation.
1424 }
1425
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001426 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1427 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001429 return ExprError();
1430 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001431 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001432}
1433
Sebastian Redl0eb23302009-01-19 00:08:26 +00001434Action::OwningExprResult
1435Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1436 ExprArg Idx, SourceLocation RLoc) {
1437 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1438 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001439
Douglas Gregor337c6b92008-11-19 17:17:41 +00001440 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001441 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001442 LHSExp->getType()->isEnumeralType() ||
1443 RHSExp->getType()->isRecordType() ||
1444 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001445 // Add the appropriate overloaded operators (C++ [over.match.oper])
1446 // to the candidate set.
1447 OverloadCandidateSet CandidateSet;
1448 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor063daf62009-03-13 18:40:31 +00001449 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1450 SourceRange(LLoc, RLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001451
Douglas Gregor337c6b92008-11-19 17:17:41 +00001452 // Perform overload resolution.
1453 OverloadCandidateSet::iterator Best;
1454 switch (BestViableFunction(CandidateSet, Best)) {
1455 case OR_Success: {
1456 // We found a built-in operator or an overloaded operator.
1457 FunctionDecl *FnDecl = Best->Function;
1458
1459 if (FnDecl) {
1460 // We matched an overloaded operator. Build a call to that
1461 // operator.
1462
1463 // Convert the arguments.
1464 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1465 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1466 PerformCopyInitialization(RHSExp,
1467 FnDecl->getParamDecl(0)->getType(),
1468 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001469 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001470 } else {
1471 // Convert the arguments.
1472 if (PerformCopyInitialization(LHSExp,
1473 FnDecl->getParamDecl(0)->getType(),
1474 "passing") ||
1475 PerformCopyInitialization(RHSExp,
1476 FnDecl->getParamDecl(1)->getType(),
1477 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001478 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001479 }
1480
1481 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001482 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001483 = FnDecl->getType()->getAsFunctionType()->getResultType();
1484 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001485
Douglas Gregor337c6b92008-11-19 17:17:41 +00001486 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001487 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1488 SourceLocation());
Douglas Gregor337c6b92008-11-19 17:17:41 +00001489 UsualUnaryConversions(FnExpr);
1490
Sebastian Redl0eb23302009-01-19 00:08:26 +00001491 Base.release();
1492 Idx.release();
Douglas Gregor063daf62009-03-13 18:40:31 +00001493 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1494 FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001495 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001496 } else {
1497 // We matched a built-in operator. Convert the arguments, then
1498 // break out so that we will build the appropriate built-in
1499 // operator node.
1500 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1501 "passing") ||
1502 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1503 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001504 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001505
1506 break;
1507 }
1508 }
1509
1510 case OR_No_Viable_Function:
1511 // No viable function; fall through to handling this as a
1512 // built-in operator, which will produce an error message for us.
1513 break;
1514
1515 case OR_Ambiguous:
1516 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1517 << "[]"
1518 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1519 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001520 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001521
1522 case OR_Deleted:
1523 Diag(LLoc, diag::err_ovl_deleted_oper)
1524 << Best->Function->isDeleted()
1525 << "[]"
1526 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1527 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1528 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001529 }
1530
1531 // Either we found no viable overloaded operator or we matched a
1532 // built-in operator. In either case, fall through to trying to
1533 // build a built-in operation.
1534 }
1535
Chris Lattner12d9ff62007-07-16 00:14:47 +00001536 // Perform default conversions.
1537 DefaultFunctionArrayConversion(LHSExp);
1538 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001539
Chris Lattner12d9ff62007-07-16 00:14:47 +00001540 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001541
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001543 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001544 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001546 Expr *BaseExpr, *IndexExpr;
1547 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001548 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1549 BaseExpr = LHSExp;
1550 IndexExpr = RHSExp;
1551 ResultType = Context.DependentTy;
1552 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001553 BaseExpr = LHSExp;
1554 IndexExpr = RHSExp;
1555 // FIXME: need to deal with const...
1556 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001557 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001558 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001559 BaseExpr = RHSExp;
1560 IndexExpr = LHSExp;
1561 // FIXME: need to deal with const...
1562 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001563 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1564 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001565 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001566
Chris Lattner12d9ff62007-07-16 00:14:47 +00001567 // FIXME: need to deal with const...
1568 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001570 return ExprError(Diag(LHSExp->getLocStart(),
1571 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1572 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 // C99 6.5.2.1p1
Sebastian Redl28507842009-02-26 14:39:58 +00001574 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001575 return ExprError(Diag(IndexExpr->getLocStart(),
1576 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001577
Chris Lattner12d9ff62007-07-16 00:14:47 +00001578 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1579 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001580 // void (*)(int)) and pointers to incomplete types. Functions are not
1581 // objects in C99.
Sebastian Redl28507842009-02-26 14:39:58 +00001582 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001583 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001584 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001585 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001586
Sebastian Redl0eb23302009-01-19 00:08:26 +00001587 Base.release();
1588 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001589 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001590 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001591}
1592
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001593QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001594CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001595 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001596 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001597
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001598 // The vector accessor can't exceed the number of elements.
1599 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001600
Mike Stumpeed9cac2009-02-19 03:04:26 +00001601 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001602 // special names that indicate a subset of exactly half the elements are
1603 // to be selected.
1604 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001605
Nate Begeman353417a2009-01-18 01:47:54 +00001606 // This flag determines whether or not CompName has an 's' char prefix,
1607 // indicating that it is a string of hex values to be used as vector indices.
1608 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001609
1610 // Check that we've found one of the special components, or that the component
1611 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001612 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001613 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1614 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001615 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001616 do
1617 compStr++;
1618 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001619 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001620 do
1621 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001622 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001623 }
Nate Begeman353417a2009-01-18 01:47:54 +00001624
Mike Stumpeed9cac2009-02-19 03:04:26 +00001625 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001626 // We didn't get to the end of the string. This means the component names
1627 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001628 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1629 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001630 return QualType();
1631 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001632
Nate Begeman353417a2009-01-18 01:47:54 +00001633 // Ensure no component accessor exceeds the width of the vector type it
1634 // operates on.
1635 if (!HalvingSwizzle) {
1636 compStr = CompName.getName();
1637
1638 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001639 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001640
1641 while (*compStr) {
1642 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1643 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1644 << baseType << SourceRange(CompLoc);
1645 return QualType();
1646 }
1647 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001648 }
Nate Begeman8a997642008-05-09 06:41:27 +00001649
Nate Begeman353417a2009-01-18 01:47:54 +00001650 // If this is a halving swizzle, verify that the base type has an even
1651 // number of elements.
1652 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001653 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001654 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001655 return QualType();
1656 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001657
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001658 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001659 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001660 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001661 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001662 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001663 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1664 : CompName.getLength();
1665 if (HexSwizzle)
1666 CompSize--;
1667
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001668 if (CompSize == 1)
1669 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001670
Nate Begeman213541a2008-04-18 23:10:10 +00001671 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001672 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001673 // diagostics look bad. We want extended vector types to appear built-in.
1674 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1675 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1676 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001677 }
1678 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001679}
1680
Chris Lattner76a642f2009-02-15 22:43:40 +00001681
Sebastian Redl0eb23302009-01-19 00:08:26 +00001682Action::OwningExprResult
1683Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1684 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001685 IdentifierInfo &Member,
1686 DeclTy *ObjCImpDecl) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001687 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001688 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001689
1690 // Perform default conversions.
1691 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001692
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001693 QualType BaseType = BaseExpr->getType();
1694 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001695
Chris Lattner68a057b2008-07-21 04:36:39 +00001696 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1697 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001699 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001700 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001701 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001702 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1703 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001704 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001705 return ExprError(Diag(MemberLoc,
1706 diag::err_typecheck_member_reference_arrow)
1707 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001709
Chris Lattner68a057b2008-07-21 04:36:39 +00001710 // Handle field access to simple records. This also handles access to fields
1711 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001712 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001713 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00001714 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001715 diag::err_typecheck_incomplete_tag,
1716 BaseExpr->getSourceRange()))
1717 return ExprError();
1718
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001719 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001720 // FIXME: Qualified name lookup for C++ is a bit more complicated
1721 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001722 LookupResult Result
Mike Stumpeed9cac2009-02-19 03:04:26 +00001723 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001724 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001725
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001726 NamedDecl *MemberDecl = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001727 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001728 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1729 << &Member << BaseExpr->getSourceRange());
1730 else if (Result.isAmbiguous()) {
1731 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1732 MemberLoc, BaseExpr->getSourceRange());
1733 return ExprError();
1734 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001735 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001736
Chris Lattner56cd21b2009-02-13 22:08:30 +00001737 // If the decl being referenced had an error, return an error for this
1738 // sub-expr without emitting another error, in order to avoid cascading
1739 // error cases.
1740 if (MemberDecl->isInvalidDecl())
1741 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001742
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001743 // Check the use of this field
1744 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1745 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00001746
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001747 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001748 // We may have found a field within an anonymous union or struct
1749 // (C++ [class.union]).
1750 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001751 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001752 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001753
Douglas Gregor86f19402008-12-20 23:49:58 +00001754 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1755 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001756 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001757 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1758 MemberType = Ref->getPointeeType();
1759 else {
1760 unsigned combinedQualifiers =
1761 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001762 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001763 combinedQualifiers &= ~QualType::Const;
1764 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1765 }
Eli Friedman51019072008-02-06 22:48:16 +00001766
Steve Naroff6ece14c2009-01-21 00:14:39 +00001767 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1768 MemberLoc, MemberType));
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001769 } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001770 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001771 Var, MemberLoc,
1772 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001773 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001774 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001775 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001776 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001777 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001778 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001779 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001780 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00001781 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1782 Enum, MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001783 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001784 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1785 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001786
Douglas Gregor86f19402008-12-20 23:49:58 +00001787 // We found a declaration kind that we didn't expect. This is a
1788 // generic error message that tells the user that she can't refer
1789 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001790 return ExprError(Diag(MemberLoc,
1791 diag::err_typecheck_member_reference_unknown)
1792 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001793 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001794
Chris Lattnera38e6b12008-07-21 04:59:05 +00001795 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1796 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001797 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001798 ObjCInterfaceDecl *ClassDeclared;
1799 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1800 ClassDeclared)) {
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 (IV->isInvalidDecl())
1805 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001806
1807 // Check whether we can reference this field.
1808 if (DiagnoseUseOfDecl(IV, MemberLoc))
1809 return ExprError();
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001810 if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1811 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1812 if (ObjCMethodDecl *MD = getCurMethodDecl())
1813 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001814 else if (ObjCImpDecl && getCurFunctionDecl()) {
1815 // Case of a c-function declared inside an objc implementation.
1816 // FIXME: For a c-style function nested inside an objc implementation
1817 // class, there is no implementation context available, so we pass down
1818 // the context as argument to this routine. Ideally, this context need
1819 // be passed down in the AST node and somehow calculated from the AST
1820 // for a function decl.
1821 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1822 if (ObjCImplementationDecl *IMPD =
1823 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1824 ClassOfMethodDecl = IMPD->getClassInterface();
1825 else if (ObjCCategoryImplDecl* CatImplClass =
1826 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1827 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Naroffb06d8752009-03-04 18:34:24 +00001828 }
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001829 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001830 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00001831 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahanian935fd762009-03-03 01:21:12 +00001832 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1833 }
1834 // @protected
1835 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1836 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1837 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001838
1839 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff6ece14c2009-01-21 00:14:39 +00001840 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001841 OpKind == tok::arrow);
1842 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001843 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001844 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001845 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1846 << IFTy->getDecl()->getDeclName() << &Member
1847 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001848 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001849
Chris Lattnera38e6b12008-07-21 04:59:05 +00001850 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1851 // pointer to a (potentially qualified) interface type.
1852 const PointerType *PTy;
1853 const ObjCInterfaceType *IFTy;
1854 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1855 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1856 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001857
Daniel Dunbar2307d312008-09-03 01:05:41 +00001858 // Search for a declared property first.
Chris Lattner7eba82e2009-02-16 18:35:08 +00001859 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001860 // Check whether we can reference this property.
1861 if (DiagnoseUseOfDecl(PD, MemberLoc))
1862 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001863
Steve Naroff6ece14c2009-01-21 00:14:39 +00001864 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001865 MemberLoc, BaseExpr));
1866 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001867
Daniel Dunbar2307d312008-09-03 01:05:41 +00001868 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001869 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1870 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner7eba82e2009-02-16 18:35:08 +00001871 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001872 // Check whether we can reference this property.
1873 if (DiagnoseUseOfDecl(PD, MemberLoc))
1874 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00001875
Steve Naroff6ece14c2009-01-21 00:14:39 +00001876 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001877 MemberLoc, BaseExpr));
1878 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001879
1880 // If that failed, look for an "implicit" property by seeing if the nullary
1881 // selector is implemented.
1882
1883 // FIXME: The logic for looking up nullary and unary selectors should be
1884 // shared with the code in ActOnInstanceMessage.
1885
1886 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1887 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001888
Daniel Dunbar2307d312008-09-03 01:05:41 +00001889 // If this reference is in an @implementation, check for 'private' methods.
1890 if (!Getter)
Steve Narofff1787282009-03-11 15:15:01 +00001891 if (ObjCImplementationDecl *ImpDecl =
1892 ObjCImplementations[IFace->getIdentifier()])
1893 Getter = ImpDecl->getInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001894
Steve Naroff7692ed62008-10-22 19:16:27 +00001895 // Look through local category implementations associated with the class.
1896 if (!Getter) {
1897 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1898 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1899 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1900 }
1901 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001902 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001903 // Check if we can reference this property.
1904 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1905 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00001906 }
1907 // If we found a getter then this may be a valid dot-reference, we
1908 // will look for the matching setter, in case it is needed.
1909 Selector SetterSel =
1910 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1911 PP.getSelectorTable(), &Member);
1912 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1913 if (!Setter) {
1914 // If this reference is in an @implementation, also check for 'private'
1915 // methods.
Steve Narofff1787282009-03-11 15:15:01 +00001916 if (ObjCImplementationDecl *ImpDecl =
1917 ObjCImplementations[IFace->getIdentifier()])
1918 Setter = ImpDecl->getInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00001919 }
1920 // Look through local category implementations associated with the class.
1921 if (!Setter) {
1922 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1923 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1924 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001925 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001926 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001927
Steve Naroff1ca66942009-03-11 13:48:17 +00001928 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1929 return ExprError();
1930
1931 if (Getter || Setter) {
1932 QualType PType;
1933
1934 if (Getter)
1935 PType = Getter->getResultType();
1936 else {
1937 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
1938 E = Setter->param_end(); PI != E; ++PI)
1939 PType = (*PI)->getType();
1940 }
1941 // FIXME: we must check that the setter has property type.
1942 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
1943 Setter, MemberLoc, BaseExpr));
1944 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001945 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1946 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001947 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001948 // Handle properties on qualified "id" protocols.
1949 const ObjCQualifiedIdType *QIdTy;
1950 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1951 // Check protocols on qualified interfaces.
1952 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001953 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner7eba82e2009-02-16 18:35:08 +00001954 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001955 // Check the use of this declaration
1956 if (DiagnoseUseOfDecl(PD, MemberLoc))
1957 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001958
Steve Naroff6ece14c2009-01-21 00:14:39 +00001959 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00001960 MemberLoc, BaseExpr));
1961 }
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001962 // Also must look for a getter name which uses property syntax.
1963 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1964 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001965 // Check the use of this method.
1966 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1967 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001968
1969 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001970 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001971 }
1972 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001973
1974 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1975 << &Member << BaseType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001976 }
Steve Naroffdd53eb52009-03-05 20:12:00 +00001977 // Handle properties on ObjC 'Class' types.
1978 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
1979 // Also must look for a getter name which uses property syntax.
1980 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1981 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff335c6802009-03-11 20:12:18 +00001982 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1983 ObjCMethodDecl *Getter;
Steve Naroffdd53eb52009-03-05 20:12:00 +00001984 // FIXME: need to also look locally in the implementation.
Steve Naroff335c6802009-03-11 20:12:18 +00001985 if ((Getter = IFace->lookupClassMethod(Sel))) {
Steve Naroffdd53eb52009-03-05 20:12:00 +00001986 // Check the use of this method.
Steve Naroff335c6802009-03-11 20:12:18 +00001987 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffdd53eb52009-03-05 20:12:00 +00001988 return ExprError();
Steve Naroffdd53eb52009-03-05 20:12:00 +00001989 }
Steve Naroff335c6802009-03-11 20:12:18 +00001990 // If we found a getter then this may be a valid dot-reference, we
1991 // will look for the matching setter, in case it is needed.
1992 Selector SetterSel =
1993 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1994 PP.getSelectorTable(), &Member);
1995 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1996 if (!Setter) {
1997 // If this reference is in an @implementation, also check for 'private'
1998 // methods.
1999 if (ObjCImplementationDecl *ImpDecl =
2000 ObjCImplementations[IFace->getIdentifier()])
2001 Setter = ImpDecl->getInstanceMethod(SetterSel);
2002 }
2003 // Look through local category implementations associated with the class.
2004 if (!Setter) {
2005 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2006 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2007 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2008 }
2009 }
2010
2011 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2012 return ExprError();
2013
2014 if (Getter || Setter) {
2015 QualType PType;
2016
2017 if (Getter)
2018 PType = Getter->getResultType();
2019 else {
2020 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2021 E = Setter->param_end(); PI != E; ++PI)
2022 PType = (*PI)->getType();
2023 }
2024 // FIXME: we must check that the setter has property type.
2025 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2026 Setter, MemberLoc, BaseExpr));
2027 }
2028 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2029 << &Member << BaseType);
Steve Naroffdd53eb52009-03-05 20:12:00 +00002030 }
2031 }
2032
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002033 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002034 if (BaseType->isExtVectorType()) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002035 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2036 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002037 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002038 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002039 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002040 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002041
2042 return ExprError(Diag(MemberLoc,
2043 diag::err_typecheck_member_reference_struct_union)
2044 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002045}
2046
Douglas Gregor88a35142008-12-22 05:46:06 +00002047/// ConvertArgumentsForCall - Converts the arguments specified in
2048/// Args/NumArgs to the parameter types of the function FDecl with
2049/// function prototype Proto. Call is the call expression itself, and
2050/// Fn is the function expression. For a C++ member function, this
2051/// routine does not attempt to convert the object argument. Returns
2052/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002053bool
2054Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002055 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002056 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002057 Expr **Args, unsigned NumArgs,
2058 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002059 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002060 // assignment, to the types of the corresponding parameter, ...
2061 unsigned NumArgsInProto = Proto->getNumArgs();
2062 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002063 bool Invalid = false;
2064
Douglas Gregor88a35142008-12-22 05:46:06 +00002065 // If too few arguments are available (and we don't have default
2066 // arguments for the remaining parameters), don't make the call.
2067 if (NumArgs < NumArgsInProto) {
2068 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2069 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2070 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2071 // Use default arguments for missing arguments
2072 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002073 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002074 }
2075
2076 // If too many are passed and not variadic, error on the extras and drop
2077 // them.
2078 if (NumArgs > NumArgsInProto) {
2079 if (!Proto->isVariadic()) {
2080 Diag(Args[NumArgsInProto]->getLocStart(),
2081 diag::err_typecheck_call_too_many_args)
2082 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2083 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2084 Args[NumArgs-1]->getLocEnd());
2085 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002086 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002087 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002088 }
2089 NumArgsToCheck = NumArgsInProto;
2090 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002091
Douglas Gregor88a35142008-12-22 05:46:06 +00002092 // Continue to check argument types (even if we have too few/many args).
2093 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2094 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002095
Douglas Gregor88a35142008-12-22 05:46:06 +00002096 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002097 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002098 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002099
2100 // Pass the argument.
2101 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2102 return true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002103 } else
Douglas Gregor61366e92008-12-24 00:01:03 +00002104 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00002105 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00002106 QualType ArgType = Arg->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002107
Douglas Gregor88a35142008-12-22 05:46:06 +00002108 Call->setArg(i, Arg);
2109 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002110
Douglas Gregor88a35142008-12-22 05:46:06 +00002111 // If this is a variadic call, handle args passed through "...".
2112 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002113 VariadicCallType CallType = VariadicFunction;
2114 if (Fn->getType()->isBlockPointerType())
2115 CallType = VariadicBlock; // Block
2116 else if (isa<MemberExpr>(Fn))
2117 CallType = VariadicMethod;
2118
Douglas Gregor88a35142008-12-22 05:46:06 +00002119 // Promote the arguments (C99 6.5.2.2p7).
2120 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2121 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002122 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002123 Call->setArg(i, Arg);
2124 }
2125 }
2126
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002127 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002128}
2129
Steve Narofff69936d2007-09-16 03:34:24 +00002130/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002131/// This provides the location of the left/right parens and a list of comma
2132/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002133Action::OwningExprResult
2134Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2135 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002136 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002137 unsigned NumArgs = args.size();
2138 Expr *Fn = static_cast<Expr *>(fn.release());
2139 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002140 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002141 FunctionDecl *FDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002142 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00002143
Douglas Gregor88a35142008-12-22 05:46:06 +00002144 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00002145 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002146 // in which case we won't do any semantic analysis now.
Douglas Gregor17330012009-02-04 15:01:18 +00002147 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2148 bool Dependent = false;
2149 if (Fn->isTypeDependent())
2150 Dependent = true;
2151 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2152 Dependent = true;
2153
2154 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002155 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002156 Context.DependentTy, RParenLoc));
2157
2158 // Determine whether this is a call to an object (C++ [over.call.object]).
2159 if (Fn->getType()->isRecordType())
2160 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2161 CommaLocs, RParenLoc));
2162
Douglas Gregorfa047642009-02-04 00:32:51 +00002163 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00002164 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2165 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2166 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002167 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2168 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00002169 }
2170
Douglas Gregorfa047642009-02-04 00:32:51 +00002171 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00002172 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00002173 Expr *FnExpr = Fn;
2174 bool ADL = true;
2175 while (true) {
2176 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2177 FnExpr = IcExpr->getSubExpr();
2178 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002179 // Parentheses around a function disable ADL
Douglas Gregor17330012009-02-04 15:01:18 +00002180 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00002181 ADL = false;
2182 FnExpr = PExpr->getSubExpr();
2183 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00002184 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregorfa047642009-02-04 00:32:51 +00002185 == UnaryOperator::AddrOf) {
2186 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattner90e150d2009-02-14 07:22:29 +00002187 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2188 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2189 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2190 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002191 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner90e150d2009-02-14 07:22:29 +00002192 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2193 UnqualifiedName = DepName->getName();
2194 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002195 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00002196 // Any kind of name that does not refer to a declaration (or
2197 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2198 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00002199 break;
2200 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002201 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002202
Douglas Gregor17330012009-02-04 15:01:18 +00002203 OverloadedFunctionDecl *Ovl = 0;
2204 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002205 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00002206 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2207 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002208
Douglas Gregorf9201e02009-02-11 23:02:49 +00002209 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002210 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002211 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002212 ADL = false;
2213
Douglas Gregorf9201e02009-02-11 23:02:49 +00002214 // We don't perform ADL in C.
2215 if (!getLangOptions().CPlusPlus)
2216 ADL = false;
2217
Douglas Gregor17330012009-02-04 15:01:18 +00002218 if (Ovl || ADL) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002219 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2220 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002221 NumArgs, CommaLocs, RParenLoc, ADL);
2222 if (!FDecl)
2223 return ExprError();
2224
2225 // Update Fn to refer to the actual function selected.
2226 Expr *NewFn = 0;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002227 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00002228 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002229 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2230 QDRExpr->getLocation(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002231 false, false,
2232 QDRExpr->getSourceRange().getBegin());
2233 else
Mike Stumpeed9cac2009-02-19 03:04:26 +00002234 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002235 Fn->getSourceRange().getBegin());
2236 Fn->Destroy(Context);
2237 Fn = NewFn;
2238 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002239 }
Chris Lattner04421082008-04-08 04:40:51 +00002240
2241 // Promote the function operand.
2242 UsualUnaryConversions(Fn);
2243
Chris Lattner925e60d2007-12-28 05:29:59 +00002244 // Make the call expr early, before semantic checks. This guarantees cleanup
2245 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002246 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2247 Args, NumArgs,
2248 Context.BoolTy,
2249 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002250
Steve Naroffdd972f22008-09-05 22:11:13 +00002251 const FunctionType *FuncT;
2252 if (!Fn->getType()->isBlockPointerType()) {
2253 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2254 // have type pointer to function".
2255 const PointerType *PT = Fn->getType()->getAsPointerType();
2256 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002257 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2258 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002259 FuncT = PT->getPointeeType()->getAsFunctionType();
2260 } else { // This is a block call.
2261 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2262 getAsFunctionType();
2263 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002264 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002265 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2266 << Fn->getType() << Fn->getSourceRange());
2267
Chris Lattner925e60d2007-12-28 05:29:59 +00002268 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002269 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002270
Douglas Gregor72564e72009-02-26 23:50:07 +00002271 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002272 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002273 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002274 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002275 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002276 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002277
Steve Naroffb291ab62007-08-28 23:30:39 +00002278 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002279 for (unsigned i = 0; i != NumArgs; i++) {
2280 Expr *Arg = Args[i];
2281 DefaultArgumentPromotion(Arg);
2282 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002283 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002285
Douglas Gregor88a35142008-12-22 05:46:06 +00002286 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2287 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002288 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2289 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002290
Chris Lattner59907c42007-08-10 20:18:51 +00002291 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00002292 if (FDecl)
2293 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00002294
Sebastian Redl0eb23302009-01-19 00:08:26 +00002295 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002296}
2297
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002298Action::OwningExprResult
2299Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2300 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002301 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002302 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002303 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002304 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002305 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002306
Eli Friedman6223c222008-05-20 05:22:08 +00002307 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002308 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002309 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2310 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor86447ec2009-03-09 16:13:40 +00002311 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002312 diag::err_typecheck_decl_incomplete_type,
2313 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002314 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002315
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002316 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002317 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002318 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002319
Chris Lattner371f2582008-12-04 23:50:19 +00002320 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002321 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002322 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002323 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002324 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002325 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002326 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002327 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002328}
2329
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002330Action::OwningExprResult
2331Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2332 InitListDesignations &Designators,
2333 SourceLocation RBraceLoc) {
2334 unsigned NumInit = initlist.size();
2335 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002336
Steve Naroff08d92e42007-09-15 18:49:24 +00002337 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00002338 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002339
Mike Stumpeed9cac2009-02-19 03:04:26 +00002340 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002341 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002342 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002343 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002344}
2345
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002346/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002347bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002348 UsualUnaryConversions(castExpr);
2349
2350 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2351 // type needs to be scalar.
2352 if (castType->isVoidType()) {
2353 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002354 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2355 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002356 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002357 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2358 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2359 (castType->isStructureType() || castType->isUnionType())) {
2360 // GCC struct/union extension: allow cast to self.
2361 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2362 << castType << castExpr->getSourceRange();
2363 } else if (castType->isUnionType()) {
2364 // GCC cast to union extension
2365 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2366 RecordDecl::field_iterator Field, FieldEnd;
2367 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2368 Field != FieldEnd; ++Field) {
2369 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2370 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2371 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2372 << castExpr->getSourceRange();
2373 break;
2374 }
2375 }
2376 if (Field == FieldEnd)
2377 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2378 << castExpr->getType() << castExpr->getSourceRange();
2379 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002380 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002381 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002382 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002383 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002384 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002385 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002386 return Diag(castExpr->getLocStart(),
2387 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002388 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002389 } else if (castExpr->getType()->isVectorType()) {
2390 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2391 return true;
2392 } else if (castType->isVectorType()) {
2393 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2394 return true;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002395 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Chris Lattnere6ee6ba2009-03-05 23:09:00 +00002396 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002397 }
2398 return false;
2399}
2400
Chris Lattnerfe23e212007-12-20 00:44:32 +00002401bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002402 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00002403
Anders Carlssona64db8f2007-11-27 05:51:55 +00002404 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002405 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002406 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00002407 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00002408 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002409 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002410 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002411 } else
2412 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002413 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002414 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002415
Anders Carlssona64db8f2007-11-27 05:51:55 +00002416 return false;
2417}
2418
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002419Action::OwningExprResult
2420Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2421 SourceLocation RParenLoc, ExprArg Op) {
2422 assert((Ty != 0) && (Op.get() != 0) &&
2423 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002424
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002425 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002426 QualType castType = QualType::getFromOpaquePtr(Ty);
2427
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002428 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002429 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002430 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002431 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002432}
2433
Sebastian Redl28507842009-02-26 14:39:58 +00002434/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2435/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002436/// C99 6.5.15
2437QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2438 SourceLocation QuestionLoc) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002439 UsualUnaryConversions(Cond);
2440 UsualUnaryConversions(LHS);
2441 UsualUnaryConversions(RHS);
2442 QualType CondTy = Cond->getType();
2443 QualType LHSTy = LHS->getType();
2444 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002445
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 // first, check the condition.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002447 if (!Cond->isTypeDependent()) {
2448 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2449 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2450 << CondTy;
Douglas Gregor898574e2008-12-05 23:32:09 +00002451 return QualType();
2452 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002453 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002454
Chris Lattner70d67a92008-01-06 22:42:25 +00002455 // Now check the two expressions.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002456 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor898574e2008-12-05 23:32:09 +00002457 return Context.DependentTy;
2458
Chris Lattner70d67a92008-01-06 22:42:25 +00002459 // If both operands have arithmetic type, do the usual arithmetic conversions
2460 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002461 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2462 UsualArithmeticConversions(LHS, RHS);
2463 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00002464 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002465
Chris Lattner70d67a92008-01-06 22:42:25 +00002466 // If both operands are the same structure or union type, the result is that
2467 // type.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002468 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2469 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002470 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00002471 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00002472 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002473 return LHSTy.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002474 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002475
Chris Lattner70d67a92008-01-06 22:42:25 +00002476 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002477 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002478 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2479 if (!LHSTy->isVoidType())
2480 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2481 << RHS->getSourceRange();
2482 if (!RHSTy->isVoidType())
2483 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2484 << LHS->getSourceRange();
2485 ImpCastExprToType(LHS, Context.VoidTy);
2486 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman0e724012008-06-04 19:47:51 +00002487 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002488 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002489 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2490 // the type of the other operand."
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002491 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2492 Context.isObjCObjectPointerType(LHSTy)) &&
2493 RHS->isNullPointerConstant(Context)) {
2494 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2495 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002496 }
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002497 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2498 Context.isObjCObjectPointerType(RHSTy)) &&
2499 LHS->isNullPointerConstant(Context)) {
2500 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2501 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002502 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002503
Chris Lattnerbd57d362008-01-06 22:50:31 +00002504 // Handle the case where both operands are pointers before we handle null
2505 // pointer constants in case both operands are null pointer constants.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002506 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2507 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002508 // get the "pointed to" types
2509 QualType lhptee = LHSPT->getPointeeType();
2510 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002511
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002512 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2513 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002514 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002515 // Figure out necessary qualifiers (C99 6.5.15p6)
2516 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002517 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002518 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2519 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002520 return destType;
2521 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002522 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002523 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002524 QualType destType = Context.getPointerType(destPointee);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002525 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2526 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmana541d532008-02-10 22:59:36 +00002527 return destType;
2528 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002529
Chris Lattnera119a3b2009-02-18 04:38:20 +00002530 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattnerb4650c12009-02-19 04:44:58 +00002531 // Two identical pointer types are always compatible.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002532 return LHSTy;
2533 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002534
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002535 QualType compositeType = LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002536
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002537 // If either type is an Objective-C object type then check
2538 // compatibility according to Objective-C.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002539 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002540 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002541 // If both operands are interfaces and either operand can be
2542 // assigned to the other, use that type as the composite
2543 // type. This allows
2544 // xxx ? (A*) a : (B*) b
2545 // where B is a subclass of A.
2546 //
2547 // Additionally, as for assignment, if either type is 'id'
2548 // allow silent coercion. Finally, if the types are
2549 // incompatible then make sure to use 'id' as the composite
2550 // type so the result is acceptable for sending messages to.
2551
Steve Naroff1fd03612009-02-12 19:05:07 +00002552 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002553 // It could return the composite type.
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002554 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2555 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2556 if (LHSIface && RHSIface &&
2557 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002558 compositeType = LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002559 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002560 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002561 compositeType = RHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002562 } else if (Context.isObjCIdStructType(lhptee) ||
2563 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002564 compositeType = Context.getObjCIdType();
2565 } else {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002566 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stumpeed9cac2009-02-19 03:04:26 +00002567 << LHSTy << RHSTy
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002568 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002569 QualType incompatTy = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002570 ImpCastExprToType(LHS, incompatTy);
2571 ImpCastExprToType(RHS, incompatTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002572 return incompatTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002573 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002574 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002575 rhptee.getUnqualifiedType())) {
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002576 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2577 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002578 // In this situation, we assume void* type. No especially good
2579 // reason, but this is what gcc does, and we do have to pick
2580 // to get a consistent AST.
2581 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002582 ImpCastExprToType(LHS, incompatTy);
2583 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002584 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002585 }
2586 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002587 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2588 // differently qualified versions of compatible types, the result type is
2589 // a pointer to an appropriately qualified version of the *composite*
2590 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002591 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002592 // FIXME: Need to add qualifiers
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002593 ImpCastExprToType(LHS, compositeType);
2594 ImpCastExprToType(RHS, compositeType);
Eli Friedman5835ea22008-05-16 20:37:07 +00002595 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 }
2597 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002598
Chris Lattnera119a3b2009-02-18 04:38:20 +00002599 // Selection between block pointer types is ok as long as they are the same.
2600 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2601 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2602 return LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002603
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002604 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2605 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stumpeed9cac2009-02-19 03:04:26 +00002606 // id with statically typed objects).
2607 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002608 // GCC allows qualified id and any Objective-C type to devolve to
2609 // id. Currently localizing to here until clear this should be
2610 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002611 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00002612 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002613 Context.isObjCObjectPointerType(RHSTy)) ||
2614 (RHSTy->isObjCQualifiedIdType() &&
2615 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002616 // FIXME: This is not the correct composite type. This only
2617 // happens to work because id can more or less be used anywhere,
2618 // however this may change the type of method sends.
2619 // FIXME: gcc adds some type-checking of the arguments and emits
2620 // (confusing) incompatible comparison warnings in some
2621 // cases. Investigate.
2622 QualType compositeType = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002623 ImpCastExprToType(LHS, compositeType);
2624 ImpCastExprToType(RHS, compositeType);
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002625 return compositeType;
2626 }
2627 }
2628
Chris Lattner70d67a92008-01-06 22:42:25 +00002629 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002630 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2631 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 return QualType();
2633}
2634
Steve Narofff69936d2007-09-16 03:34:24 +00002635/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002636/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002637Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2638 SourceLocation ColonLoc,
2639 ExprArg Cond, ExprArg LHS,
2640 ExprArg RHS) {
2641 Expr *CondExpr = (Expr *) Cond.get();
2642 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002643
2644 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2645 // was the condition.
2646 bool isLHSNull = LHSExpr == 0;
2647 if (isLHSNull)
2648 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002649
2650 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002651 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002653 return ExprError();
2654
2655 Cond.release();
2656 LHS.release();
2657 RHS.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002658 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002659 isLHSNull ? 0 : LHSExpr,
2660 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002661}
2662
Reid Spencer5f016e22007-07-11 17:01:13 +00002663
2664// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00002665// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00002666// routine is it effectively iqnores the qualifiers on the top level pointee.
2667// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2668// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002669Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002670Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2671 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002672
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002674 lhptee = lhsType->getAsPointerType()->getPointeeType();
2675 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002676
Reid Spencer5f016e22007-07-11 17:01:13 +00002677 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002678 lhptee = Context.getCanonicalType(lhptee);
2679 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002680
Chris Lattner5cf216b2008-01-04 18:04:52 +00002681 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002682
2683 // C99 6.5.16.1p1: This following citation is common to constraints
2684 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2685 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002686 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002687 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002688 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002689
Mike Stumpeed9cac2009-02-19 03:04:26 +00002690 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2691 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002693 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002694 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002695 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002696
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002697 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002698 assert(rhptee->isFunctionType());
2699 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002700 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002701
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002702 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002703 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002704 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002705
2706 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002707 assert(lhptee->isFunctionType());
2708 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002709 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002710 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 // unqualified versions of compatible types, ...
Mike Stumpeed9cac2009-02-19 03:04:26 +00002712 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002713 rhptee.getUnqualifiedType()))
2714 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002715 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002716}
2717
Steve Naroff1c7d0672008-09-04 15:10:53 +00002718/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2719/// block pointer types are compatible or whether a block and normal pointer
2720/// are compatible. It is more restrict than comparing two function pointer
2721// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002722Sema::AssignConvertType
2723Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00002724 QualType rhsType) {
2725 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002726
Steve Naroff1c7d0672008-09-04 15:10:53 +00002727 // get the "pointed to" type (ignoring qualifiers at the top level)
2728 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002729 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2730
Steve Naroff1c7d0672008-09-04 15:10:53 +00002731 // make sure we operate on the canonical type
2732 lhptee = Context.getCanonicalType(lhptee);
2733 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002734
Steve Naroff1c7d0672008-09-04 15:10:53 +00002735 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002736
Steve Naroff1c7d0672008-09-04 15:10:53 +00002737 // For blocks we enforce that qualifiers are identical.
2738 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2739 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002740
Steve Naroff1c7d0672008-09-04 15:10:53 +00002741 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002742 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002743 return ConvTy;
2744}
2745
Mike Stumpeed9cac2009-02-19 03:04:26 +00002746/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2747/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00002748/// pointers. Here are some objectionable examples that GCC considers warnings:
2749///
2750/// int a, *pint;
2751/// short *pshort;
2752/// struct foo *pfoo;
2753///
2754/// pint = pshort; // warning: assignment from incompatible pointer type
2755/// a = pint; // warning: assignment makes integer from pointer without a cast
2756/// pint = a; // warning: assignment makes pointer from integer without a cast
2757/// pint = pfoo; // warning: assignment from incompatible pointer type
2758///
2759/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00002760/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002761///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002762Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002763Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002764 // Get canonical types. We're not formatting these types, just comparing
2765 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002766 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2767 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002768
2769 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002770 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002771
Douglas Gregor9d293df2008-10-28 00:22:11 +00002772 // If the left-hand side is a reference type, then we are in a
2773 // (rare!) case where we've allowed the use of references in C,
2774 // e.g., as a parameter type in a built-in function. In this case,
2775 // just make sure that the type referenced is compatible with the
2776 // right-hand side type. The caller is responsible for adjusting
2777 // lhsType so that the resulting expression does not have reference
2778 // type.
2779 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2780 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002781 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002782 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002783 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002784
Chris Lattnereca7be62008-04-07 05:30:13 +00002785 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2786 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002787 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002788 // Relax integer conversions like we do for pointers below.
2789 if (rhsType->isIntegerType())
2790 return IntToPointer;
2791 if (lhsType->isIntegerType())
2792 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002793 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002794 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002795
Nate Begemanbe2341d2008-07-14 18:02:46 +00002796 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002797 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002798 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2799 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002800 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002801
Nate Begemanbe2341d2008-07-14 18:02:46 +00002802 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00002803 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00002804 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002805 if (getLangOptions().LaxVectorConversions &&
2806 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002807 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002808 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002809 }
2810 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002811 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002812
Chris Lattnere8b3e962008-01-04 23:32:24 +00002813 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002815
Chris Lattner78eca282008-04-07 06:49:41 +00002816 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002818 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002819
Chris Lattner78eca282008-04-07 06:49:41 +00002820 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002822
Steve Naroffb4406862008-09-29 18:10:17 +00002823 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002824 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002825 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002826
2827 // Treat block pointers as objects.
2828 if (getLangOptions().ObjC1 &&
2829 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2830 return Compatible;
2831 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002832 return Incompatible;
2833 }
2834
2835 if (isa<BlockPointerType>(lhsType)) {
2836 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00002837 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002838
Steve Naroffb4406862008-09-29 18:10:17 +00002839 // Treat block pointers as objects.
2840 if (getLangOptions().ObjC1 &&
2841 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2842 return Compatible;
2843
Steve Naroff1c7d0672008-09-04 15:10:53 +00002844 if (rhsType->isBlockPointerType())
2845 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002846
Steve Naroff1c7d0672008-09-04 15:10:53 +00002847 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2848 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002849 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002850 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002851 return Incompatible;
2852 }
2853
Chris Lattner78eca282008-04-07 06:49:41 +00002854 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002856 if (lhsType == Context.BoolTy)
2857 return Compatible;
2858
2859 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002860 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002861
Mike Stumpeed9cac2009-02-19 03:04:26 +00002862 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002864
2865 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff1c7d0672008-09-04 15:10:53 +00002866 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002867 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002868 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002869 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002870
Chris Lattnerfc144e22008-01-04 23:18:45 +00002871 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002872 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002874 }
2875 return Incompatible;
2876}
2877
Chris Lattner5cf216b2008-01-04 18:04:52 +00002878Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002879Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002880 if (getLangOptions().CPlusPlus) {
2881 if (!lhsType->isRecordType()) {
2882 // C++ 5.17p3: If the left operand is not of class type, the
2883 // expression is implicitly converted (C++ 4) to the
2884 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002885 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2886 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002887 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002888 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002889 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002890 }
2891
2892 // FIXME: Currently, we fall through and treat C++ classes like C
2893 // structures.
2894 }
2895
Steve Naroff529a4ad2007-11-27 17:58:44 +00002896 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2897 // a null pointer constant.
Steve Narofff7f52e72009-02-21 21:17:01 +00002898 if ((lhsType->isPointerType() ||
2899 lhsType->isObjCQualifiedIdType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00002900 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002901 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002902 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002903 return Compatible;
2904 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002905
Chris Lattner943140e2007-10-16 02:55:40 +00002906 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002907 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002908 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002909 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002910 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00002911 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002912 if (!lhsType->isReferenceType())
2913 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002914
Chris Lattner5cf216b2008-01-04 18:04:52 +00002915 Sema::AssignConvertType result =
2916 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00002917
Steve Narofff1120de2007-08-24 22:33:52 +00002918 // C99 6.5.16.1p2: The value of the right operand is converted to the
2919 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002920 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2921 // so that we can use references in built-in functions even in C.
2922 // The getNonReferenceType() call makes sure that the resulting expression
2923 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002924 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002925 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002926 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002927}
2928
Chris Lattner5cf216b2008-01-04 18:04:52 +00002929Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002930Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2931 return CheckAssignmentConstraints(lhsType, rhsType);
2932}
2933
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002934QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002935 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002936 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002937 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002938 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002939}
2940
Mike Stumpeed9cac2009-02-19 03:04:26 +00002941inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002942 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002943 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002944 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002945 QualType lhsType =
2946 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2947 QualType rhsType =
2948 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002949
Nate Begemanbe2341d2008-07-14 18:02:46 +00002950 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002951 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002952 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002953
Nate Begemanbe2341d2008-07-14 18:02:46 +00002954 // Handle the case of a vector & extvector type of the same size and element
2955 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002956 if (getLangOptions().LaxVectorConversions) {
2957 // FIXME: Should we warn here?
2958 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002959 if (const VectorType *RV = rhsType->getAsVectorType())
2960 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002961 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002962 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002963 }
2964 }
2965 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002966
Nate Begemanbe2341d2008-07-14 18:02:46 +00002967 // If the lhs is an extended vector and the rhs is a scalar of the same type
2968 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002969 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002970 QualType eltType = V->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002971
2972 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00002973 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2974 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002975 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002976 return lhsType;
2977 }
2978 }
2979
Nate Begemanbe2341d2008-07-14 18:02:46 +00002980 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002981 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002982 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002983 QualType eltType = V->getElementType();
2984
Mike Stumpeed9cac2009-02-19 03:04:26 +00002985 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00002986 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2987 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002988 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002989 return rhsType;
2990 }
2991 }
2992
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002994 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002995 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002996 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00002998}
2999
Reid Spencer5f016e22007-07-11 17:01:13 +00003000inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003001 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003002{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00003003 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003004 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003005
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003006 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003007
Steve Naroffa4332e22007-07-17 00:58:39 +00003008 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003009 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003010 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003011}
3012
3013inline QualType Sema::CheckRemainderOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003014 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003015{
Daniel Dunbar523aa602009-01-05 22:55:36 +00003016 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3017 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3018 return CheckVectorOperands(Loc, lex, rex);
3019 return InvalidOperands(Loc, lex, rex);
3020 }
Steve Naroff90045e82007-07-13 23:32:42 +00003021
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003022 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003023
Steve Naroffa4332e22007-07-17 00:58:39 +00003024 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003025 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003026 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003027}
3028
3029inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stumpeed9cac2009-02-19 03:04:26 +00003030 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003031{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003032 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003033 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00003034
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003035 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00003036
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00003038 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003039 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003040
Eli Friedmand72d16e2008-05-18 18:08:51 +00003041 // Put any potential pointer into PExp
3042 Expr* PExp = lex, *IExp = rex;
3043 if (IExp->getType()->isPointerType())
3044 std::swap(PExp, IExp);
3045
3046 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3047 if (IExp->getType()->isIntegerType()) {
3048 // Check for arithmetic on pointers to incomplete types
3049 if (!PTy->getPointeeType()->isObjectType()) {
3050 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003051 if (getLangOptions().CPlusPlus) {
3052 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3053 << lex->getSourceRange() << rex->getSourceRange();
3054 return QualType();
3055 }
3056
3057 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003058 Diag(Loc, diag::ext_gnu_void_ptr)
3059 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003060 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003061 if (getLangOptions().CPlusPlus) {
3062 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3063 << lex->getType() << lex->getSourceRange();
3064 return QualType();
3065 }
3066
3067 // GNU extension: arithmetic on pointer to function
3068 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003069 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003070 } else {
Douglas Gregor86447ec2009-03-09 16:13:40 +00003071 RequireCompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003072 diag::err_typecheck_arithmetic_incomplete_type,
3073 lex->getSourceRange(), SourceRange(),
3074 lex->getType());
3075 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00003076 }
3077 }
3078 return PExp->getType();
3079 }
3080 }
3081
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003082 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003083}
3084
Chris Lattnereca7be62008-04-07 05:30:13 +00003085// C99 6.5.6
3086QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003087 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00003088 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003089 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003090
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003091 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003092
Chris Lattner6e4ab612007-12-09 21:53:25 +00003093 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003094
Chris Lattner6e4ab612007-12-09 21:53:25 +00003095 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00003096 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003097 return compType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003098
Chris Lattner6e4ab612007-12-09 21:53:25 +00003099 // Either ptr - int or ptr - ptr.
3100 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00003101 QualType lpointee = LHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003102
Chris Lattner6e4ab612007-12-09 21:53:25 +00003103 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00003104 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00003105 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00003106 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003107 Diag(Loc, diag::ext_gnu_void_ptr)
3108 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00003109 } else if (lpointee->isFunctionType()) {
3110 if (getLangOptions().CPlusPlus) {
3111 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3112 << lex->getType() << lex->getSourceRange();
3113 return QualType();
3114 }
3115
3116 // GNU extension: arithmetic on pointer to function
3117 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3118 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003119 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003120 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00003121 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003122 return QualType();
3123 }
3124 }
3125
3126 // The result type of a pointer-int computation is the pointer type.
3127 if (rex->getType()->isIntegerType())
3128 return lex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003129
Chris Lattner6e4ab612007-12-09 21:53:25 +00003130 // Handle pointer-pointer subtractions.
3131 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00003132 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003133
Chris Lattner6e4ab612007-12-09 21:53:25 +00003134 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00003135 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00003136 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00003137 if (rpointee->isVoidType()) {
3138 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003139 Diag(Loc, diag::ext_gnu_void_ptr)
3140 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00003141 } else if (rpointee->isFunctionType()) {
3142 if (getLangOptions().CPlusPlus) {
3143 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3144 << rex->getType() << rex->getSourceRange();
3145 return QualType();
3146 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003147
Douglas Gregor08048882009-01-23 19:03:35 +00003148 // GNU extension: arithmetic on pointer to function
3149 if (!lpointee->isFunctionType())
3150 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3151 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003152 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003153 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00003154 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003155 return QualType();
3156 }
3157 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003158
Chris Lattner6e4ab612007-12-09 21:53:25 +00003159 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003160 if (!Context.typesAreCompatible(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003161 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedmanf1c7b482008-09-02 05:09:35 +00003162 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003163 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00003164 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003165 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003166 return QualType();
3167 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003168
Chris Lattner6e4ab612007-12-09 21:53:25 +00003169 return Context.getPointerDiffType();
3170 }
3171 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003172
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003173 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003174}
3175
Chris Lattnereca7be62008-04-07 05:30:13 +00003176// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003177QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003178 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00003179 // C99 6.5.7p2: Each of the operands shall have integer type.
3180 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003181 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003182
Chris Lattnerca5eede2007-12-12 05:47:28 +00003183 // Shifts don't perform usual arithmetic conversions, they just do integer
3184 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00003185 if (!isCompAssign)
3186 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00003187 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003188
Chris Lattnerca5eede2007-12-12 05:47:28 +00003189 // "The type of the result is that of the promoted left operand."
3190 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003191}
3192
Chris Lattnereca7be62008-04-07 05:30:13 +00003193// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003194QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003195 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003196 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003197 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003198
Chris Lattnera5937dd2007-08-26 01:18:55 +00003199 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00003200 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3201 UsualArithmeticConversions(lex, rex);
3202 else {
3203 UsualUnaryConversions(lex);
3204 UsualUnaryConversions(rex);
3205 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003206 QualType lType = lex->getType();
3207 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003208
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003209 if (!lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00003210 // For non-floating point types, check for self-comparisons of the form
3211 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3212 // often indicate logic errors in the program.
3213 Expr *LHSStripped = lex->IgnoreParens();
3214 Expr *RHSStripped = rex->IgnoreParens();
3215 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3216 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003217 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003218 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner55660a72009-03-08 19:39:53 +00003219
3220 if (isa<CastExpr>(LHSStripped))
3221 LHSStripped = LHSStripped->IgnoreParenCasts();
3222 if (isa<CastExpr>(RHSStripped))
3223 RHSStripped = RHSStripped->IgnoreParenCasts();
3224
3225 // Warn about comparisons against a string constant (unless the other
3226 // operand is null), the user probably wants strcmp.
3227 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3228 !RHSStripped->isNullPointerConstant(Context))
3229 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3230 else if ((isa<StringLiteral>(RHSStripped) ||
3231 isa<ObjCEncodeExpr>(RHSStripped)) &&
3232 !LHSStripped->isNullPointerConstant(Context))
3233 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003234 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003235
Douglas Gregor447b69e2008-11-19 03:25:36 +00003236 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00003237 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00003238
Chris Lattnera5937dd2007-08-26 01:18:55 +00003239 if (isRelational) {
3240 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003241 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003242 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003243 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003244 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00003245 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003246 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00003247 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003248
Chris Lattnera5937dd2007-08-26 01:18:55 +00003249 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003250 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003251 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003252
Chris Lattnerd28f8152007-08-26 01:10:14 +00003253 bool LHSIsNull = lex->isNullPointerConstant(Context);
3254 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003255
Chris Lattnera5937dd2007-08-26 01:18:55 +00003256 // All of the following pointer related warnings are GCC extensions, except
3257 // when handling null pointer constants. One day, we can consider making them
3258 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00003259 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003260 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003261 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00003262 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003263 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003264
Steve Naroff66296cb2007-11-13 14:57:38 +00003265 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003266 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3267 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00003268 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff389bf462009-02-12 17:52:19 +00003269 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003270 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003271 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003272 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00003273 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003274 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003275 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003276 // Handle block pointer types.
3277 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3278 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3279 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003280
Steve Naroff1c7d0672008-09-04 15:10:53 +00003281 if (!LHSIsNull && !RHSIsNull &&
3282 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003283 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003284 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00003285 }
3286 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003287 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003288 }
Steve Naroff59f53942008-09-28 01:11:11 +00003289 // Allow block pointers to be compared with null pointer constants.
3290 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3291 (lType->isPointerType() && rType->isBlockPointerType())) {
3292 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003293 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003294 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00003295 }
3296 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003297 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00003298 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003299
Steve Naroff20373222008-06-03 14:04:54 +00003300 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00003301 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00003302 const PointerType *LPT = lType->getAsPointerType();
3303 const PointerType *RPT = rType->getAsPointerType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003304 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003305 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003306 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00003307 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003308
Steve Naroffa8069f12008-11-17 19:49:16 +00003309 if (!LPtrToVoid && !RPtrToVoid &&
3310 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003311 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003312 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00003313 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003314 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00003315 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003316 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003317 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00003318 }
Steve Naroff20373222008-06-03 14:04:54 +00003319 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3320 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003321 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003322 } else {
3323 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003324 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003325 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003326 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003327 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003328 }
Steve Naroff20373222008-06-03 14:04:54 +00003329 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00003330 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003331 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff20373222008-06-03 14:04:54 +00003332 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003333 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003334 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003335 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003336 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003337 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003338 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003339 if (lType->isIntegerType() &&
Steve Naroff20373222008-06-03 14:04:54 +00003340 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003341 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003342 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003343 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003344 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003345 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003346 }
Steve Naroff39218df2008-09-04 16:56:14 +00003347 // Handle block pointers.
3348 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3349 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003350 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003351 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003352 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003353 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003354 }
3355 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3356 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003357 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003358 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003359 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003360 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003361 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003362 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003363}
3364
Nate Begemanbe2341d2008-07-14 18:02:46 +00003365/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00003366/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003367/// like a scalar comparison, a vector comparison produces a vector of integer
3368/// types.
3369QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003370 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003371 bool isRelational) {
3372 // Check to make sure we're operating on vectors of the same type and width,
3373 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003374 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003375 if (vType.isNull())
3376 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003377
Nate Begemanbe2341d2008-07-14 18:02:46 +00003378 QualType lType = lex->getType();
3379 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003380
Nate Begemanbe2341d2008-07-14 18:02:46 +00003381 // For non-floating point types, check for self-comparisons of the form
3382 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3383 // often indicate logic errors in the program.
3384 if (!lType->isFloatingType()) {
3385 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3386 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3387 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003388 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003389 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003390
Nate Begemanbe2341d2008-07-14 18:02:46 +00003391 // Check for comparisons of floating point operands using != and ==.
3392 if (!isRelational && lType->isFloatingType()) {
3393 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003394 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003395 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003396
Nate Begemanbe2341d2008-07-14 18:02:46 +00003397 // Return the type for the comparison, which is the same as vector type for
3398 // integer vectors, or an integer type of identical size and number of
3399 // elements for floating point vectors.
3400 if (lType->isIntegerType())
3401 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003402
Nate Begemanbe2341d2008-07-14 18:02:46 +00003403 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003404 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003405 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003406 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003407 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3408 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3409
Mike Stumpeed9cac2009-02-19 03:04:26 +00003410 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00003411 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003412 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3413}
3414
Reid Spencer5f016e22007-07-11 17:01:13 +00003415inline QualType Sema::CheckBitwiseOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003416 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003417{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003418 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003419 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003420
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003421 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003422
Steve Naroffa4332e22007-07-17 00:58:39 +00003423 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003424 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003425 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003426}
3427
3428inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stumpeed9cac2009-02-19 03:04:26 +00003429 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003430{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003431 UsualUnaryConversions(lex);
3432 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003433
Eli Friedman5773a6c2008-05-13 20:16:47 +00003434 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003435 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003436 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003437}
3438
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003439/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3440/// is a read-only property; return true if so. A readonly property expression
3441/// depends on various declarations and thus must be treated specially.
3442///
Mike Stumpeed9cac2009-02-19 03:04:26 +00003443static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003444{
3445 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3446 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3447 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3448 QualType BaseType = PropExpr->getBase()->getType();
3449 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003450 if (const ObjCInterfaceType *IFTy =
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003451 PTy->getPointeeType()->getAsObjCInterfaceType())
3452 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3453 if (S.isPropertyReadonly(PDecl, IFace))
3454 return true;
3455 }
3456 }
3457 return false;
3458}
3459
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003460/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3461/// emit an error and return true. If so, return false.
3462static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003463 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3464 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3465 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003466 if (IsLV == Expr::MLV_Valid)
3467 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003468
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003469 unsigned Diag = 0;
3470 bool NeedType = false;
3471 switch (IsLV) { // C99 6.5.16p2
3472 default: assert(0 && "Unknown result from isModifiableLvalue!");
3473 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003474 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003475 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3476 NeedType = true;
3477 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003478 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003479 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3480 NeedType = true;
3481 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003482 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003483 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3484 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003485 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003486 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3487 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003488 case Expr::MLV_IncompleteType:
3489 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00003490 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003491 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3492 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003493 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003494 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3495 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003496 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003497 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3498 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003499 case Expr::MLV_ReadonlyProperty:
3500 Diag = diag::error_readonly_property_assignment;
3501 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003502 case Expr::MLV_NoSetterProperty:
3503 Diag = diag::error_nosetter_property_assignment;
3504 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003505 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003506
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003507 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003508 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003509 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003510 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003511 return true;
3512}
3513
3514
3515
3516// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003517QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3518 SourceLocation Loc,
3519 QualType CompoundType) {
3520 // Verify that LHS is a modifiable lvalue, and emit error if not.
3521 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003522 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003523
3524 QualType LHSType = LHS->getType();
3525 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003526
Chris Lattner5cf216b2008-01-04 18:04:52 +00003527 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003528 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003529 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003530 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003531 // Special case of NSObject attributes on c-style pointer types.
3532 if (ConvTy == IncompatiblePointer &&
3533 ((Context.isObjCNSObjectType(LHSType) &&
3534 Context.isObjCObjectPointerType(RHSType)) ||
3535 (Context.isObjCNSObjectType(RHSType) &&
3536 Context.isObjCObjectPointerType(LHSType))))
3537 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003538
Chris Lattner2c156472008-08-21 18:04:13 +00003539 // If the RHS is a unary plus or minus, check to see if they = and + are
3540 // right next to each other. If so, the user may have typo'd "x =+ 4"
3541 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003542 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003543 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3544 RHSCheck = ICE->getSubExpr();
3545 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3546 if ((UO->getOpcode() == UnaryOperator::Plus ||
3547 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003548 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003549 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00003550 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3551 // And there is a space or other character before the subexpr of the
3552 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00003553 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3554 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003555 Diag(Loc, diag::warn_not_compound_assign)
3556 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3557 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00003558 }
Chris Lattner2c156472008-08-21 18:04:13 +00003559 }
3560 } else {
3561 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003562 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003563 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003564
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003565 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3566 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003567 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003568
Reid Spencer5f016e22007-07-11 17:01:13 +00003569 // C99 6.5.16p3: The type of an assignment expression is the type of the
3570 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00003571 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00003572 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3573 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003574 // C++ 5.17p1: the type of the assignment expression is that of its left
3575 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003576 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003577}
3578
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003579// C99 6.5.17
3580QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3581 // FIXME: what is required for LHS?
Mike Stumpeed9cac2009-02-19 03:04:26 +00003582
Chris Lattner53fcaa92008-07-25 20:54:07 +00003583 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003584 DefaultFunctionArrayConversion(RHS);
3585 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003586}
3587
Steve Naroff49b45262007-07-13 16:58:59 +00003588/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3589/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003590QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3591 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003592 if (Op->isTypeDependent())
3593 return Context.DependentTy;
3594
Chris Lattner3528d352008-11-21 07:05:48 +00003595 QualType ResType = Op->getType();
3596 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003597
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003598 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3599 // Decrement of bool is not allowed.
3600 if (!isInc) {
3601 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3602 return QualType();
3603 }
3604 // Increment of bool sets it to true, but is deprecated.
3605 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3606 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003607 // OK!
3608 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3609 // C99 6.5.2.4p2, 6.5.6p2
3610 if (PT->getPointeeType()->isObjectType()) {
3611 // Pointer to object is ok!
3612 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003613 if (getLangOptions().CPlusPlus) {
3614 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3615 << Op->getSourceRange();
3616 return QualType();
3617 }
3618
3619 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003620 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003621 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003622 if (getLangOptions().CPlusPlus) {
3623 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3624 << Op->getType() << Op->getSourceRange();
3625 return QualType();
3626 }
3627
3628 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003629 << ResType << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003630 } else {
Douglas Gregor86447ec2009-03-09 16:13:40 +00003631 RequireCompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003632 diag::err_typecheck_arithmetic_incomplete_type,
3633 Op->getSourceRange(), SourceRange(),
3634 ResType);
3635 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003636 }
Chris Lattner3528d352008-11-21 07:05:48 +00003637 } else if (ResType->isComplexType()) {
3638 // C99 does not support ++/-- on complex types, we allow as an extension.
3639 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003640 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003641 } else {
3642 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003643 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003644 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003645 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003646 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00003647 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003648 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003649 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003650 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003651}
3652
Anders Carlsson369dee42008-02-01 07:15:58 +00003653/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003654/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003655/// where the declaration is needed for type checking. We only need to
3656/// handle cases when the expression references a function designator
3657/// or is an lvalue. Here are some examples:
3658/// - &(x) => x
3659/// - &*****f => f for f a function designator.
3660/// - &s.xx => s
3661/// - &s.zz[1].yy -> s, if zz is an array
3662/// - *(x + 1) -> x, if x is an array
3663/// - &"123"[2] -> 0
3664/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003665static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003666 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003667 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003668 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003669 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003670 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003671 // Fields cannot be declared with a 'register' storage class.
3672 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003673 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003674 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003675 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003676 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003677 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003678
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003679 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003680 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003681 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003682 return 0;
3683 else
3684 return VD;
3685 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003686 case Stmt::UnaryOperatorClass: {
3687 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003688
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003689 switch(UO->getOpcode()) {
3690 case UnaryOperator::Deref: {
3691 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003692 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3693 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3694 if (!VD || VD->getType()->isPointerType())
3695 return 0;
3696 return VD;
3697 }
3698 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003699 }
3700 case UnaryOperator::Real:
3701 case UnaryOperator::Imag:
3702 case UnaryOperator::Extension:
3703 return getPrimaryDecl(UO->getSubExpr());
3704 default:
3705 return 0;
3706 }
3707 }
3708 case Stmt::BinaryOperatorClass: {
3709 BinaryOperator *BO = cast<BinaryOperator>(E);
3710
3711 // Handle cases involving pointer arithmetic. The result of an
3712 // Assign or AddAssign is not an lvalue so they can be ignored.
3713
3714 // (x + n) or (n + x) => x
3715 if (BO->getOpcode() == BinaryOperator::Add) {
3716 if (BO->getLHS()->getType()->isPointerType()) {
3717 return getPrimaryDecl(BO->getLHS());
3718 } else if (BO->getRHS()->getType()->isPointerType()) {
3719 return getPrimaryDecl(BO->getRHS());
3720 }
3721 }
3722
3723 return 0;
3724 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003725 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003726 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003727 case Stmt::ImplicitCastExprClass:
3728 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003729 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003730 default:
3731 return 0;
3732 }
3733}
3734
3735/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00003736/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00003737/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003738/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00003739/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003740/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00003741/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003742QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003743 if (op->isTypeDependent())
3744 return Context.DependentTy;
3745
Steve Naroff08f19672008-01-13 17:10:08 +00003746 if (getLangOptions().C99) {
3747 // Implement C99-only parts of addressof rules.
3748 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3749 if (uOp->getOpcode() == UnaryOperator::Deref)
3750 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3751 // (assuming the deref expression is valid).
3752 return uOp->getSubExpr()->getType();
3753 }
3754 // Technically, there should be a check for array subscript
3755 // expressions here, but the result of one is always an lvalue anyway.
3756 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003757 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003758 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003759
Reid Spencer5f016e22007-07-11 17:01:13 +00003760 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003761 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3762 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003763 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3764 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003765 return QualType();
3766 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003767 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003768 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3769 if (Field->isBitField()) {
3770 Diag(OpLoc, diag::err_typecheck_address_of)
3771 << "bit-field" << op->getSourceRange();
3772 return QualType();
3773 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003774 }
3775 // Check for Apple extension for accessing vector components.
Nate Begemanb104b1f2009-02-15 22:45:20 +00003776 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3777 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003778 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00003779 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003780 return QualType();
3781 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00003782 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00003783 // with the register storage-class specifier.
3784 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3785 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003786 Diag(OpLoc, diag::err_typecheck_address_of)
3787 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003788 return QualType();
3789 }
Douglas Gregor29882052008-12-10 21:26:49 +00003790 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003791 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003792 } else if (isa<FieldDecl>(dcl)) {
3793 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00003794 // Could be a pointer to member, though, if there is an explicit
3795 // scope qualifier for the class.
3796 if (isa<QualifiedDeclRefExpr>(op)) {
3797 DeclContext *Ctx = dcl->getDeclContext();
3798 if (Ctx && Ctx->isRecord())
3799 return Context.getMemberPointerType(op->getType(),
3800 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3801 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003802 } else if (isa<FunctionDecl>(dcl)) {
3803 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00003804 // As above.
3805 if (isa<QualifiedDeclRefExpr>(op)) {
3806 DeclContext *Ctx = dcl->getDeclContext();
3807 if (Ctx && Ctx->isRecord())
3808 return Context.getMemberPointerType(op->getType(),
3809 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3810 }
Douglas Gregor29882052008-12-10 21:26:49 +00003811 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003812 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003813 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003814 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00003815
Reid Spencer5f016e22007-07-11 17:01:13 +00003816 // If the operand has type "type", the result has type "pointer to type".
3817 return Context.getPointerType(op->getType());
3818}
3819
Chris Lattner22caddc2008-11-23 09:13:29 +00003820QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00003821 if (Op->isTypeDependent())
3822 return Context.DependentTy;
3823
Chris Lattner22caddc2008-11-23 09:13:29 +00003824 UsualUnaryConversions(Op);
3825 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003826
Chris Lattner22caddc2008-11-23 09:13:29 +00003827 // Note that per both C89 and C99, this is always legal, even if ptype is an
3828 // incomplete type or void. It would be possible to warn about dereferencing
3829 // a void pointer, but it's completely well-defined, and such a warning is
3830 // unlikely to catch any mistakes.
3831 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003832 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003833
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003834 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003835 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003836 return QualType();
3837}
3838
3839static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3840 tok::TokenKind Kind) {
3841 BinaryOperator::Opcode Opc;
3842 switch (Kind) {
3843 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00003844 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3845 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003846 case tok::star: Opc = BinaryOperator::Mul; break;
3847 case tok::slash: Opc = BinaryOperator::Div; break;
3848 case tok::percent: Opc = BinaryOperator::Rem; break;
3849 case tok::plus: Opc = BinaryOperator::Add; break;
3850 case tok::minus: Opc = BinaryOperator::Sub; break;
3851 case tok::lessless: Opc = BinaryOperator::Shl; break;
3852 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3853 case tok::lessequal: Opc = BinaryOperator::LE; break;
3854 case tok::less: Opc = BinaryOperator::LT; break;
3855 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3856 case tok::greater: Opc = BinaryOperator::GT; break;
3857 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3858 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3859 case tok::amp: Opc = BinaryOperator::And; break;
3860 case tok::caret: Opc = BinaryOperator::Xor; break;
3861 case tok::pipe: Opc = BinaryOperator::Or; break;
3862 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3863 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3864 case tok::equal: Opc = BinaryOperator::Assign; break;
3865 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3866 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3867 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3868 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3869 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3870 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3871 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3872 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3873 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3874 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3875 case tok::comma: Opc = BinaryOperator::Comma; break;
3876 }
3877 return Opc;
3878}
3879
3880static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3881 tok::TokenKind Kind) {
3882 UnaryOperator::Opcode Opc;
3883 switch (Kind) {
3884 default: assert(0 && "Unknown unary op!");
3885 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3886 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3887 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3888 case tok::star: Opc = UnaryOperator::Deref; break;
3889 case tok::plus: Opc = UnaryOperator::Plus; break;
3890 case tok::minus: Opc = UnaryOperator::Minus; break;
3891 case tok::tilde: Opc = UnaryOperator::Not; break;
3892 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003893 case tok::kw___real: Opc = UnaryOperator::Real; break;
3894 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3895 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3896 }
3897 return Opc;
3898}
3899
Douglas Gregoreaebc752008-11-06 23:29:22 +00003900/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3901/// operator @p Opc at location @c TokLoc. This routine only supports
3902/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003903Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3904 unsigned Op,
3905 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003906 QualType ResultTy; // Result type of the binary operator.
3907 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3908 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3909
3910 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003911 case BinaryOperator::Assign:
3912 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3913 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003914 case BinaryOperator::PtrMemD:
3915 case BinaryOperator::PtrMemI:
3916 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3917 Opc == BinaryOperator::PtrMemI);
3918 break;
3919 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003920 case BinaryOperator::Div:
3921 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3922 break;
3923 case BinaryOperator::Rem:
3924 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3925 break;
3926 case BinaryOperator::Add:
3927 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3928 break;
3929 case BinaryOperator::Sub:
3930 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3931 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003932 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003933 case BinaryOperator::Shr:
3934 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3935 break;
3936 case BinaryOperator::LE:
3937 case BinaryOperator::LT:
3938 case BinaryOperator::GE:
3939 case BinaryOperator::GT:
3940 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3941 break;
3942 case BinaryOperator::EQ:
3943 case BinaryOperator::NE:
3944 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3945 break;
3946 case BinaryOperator::And:
3947 case BinaryOperator::Xor:
3948 case BinaryOperator::Or:
3949 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3950 break;
3951 case BinaryOperator::LAnd:
3952 case BinaryOperator::LOr:
3953 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3954 break;
3955 case BinaryOperator::MulAssign:
3956 case BinaryOperator::DivAssign:
3957 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3958 if (!CompTy.isNull())
3959 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3960 break;
3961 case BinaryOperator::RemAssign:
3962 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3963 if (!CompTy.isNull())
3964 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3965 break;
3966 case BinaryOperator::AddAssign:
3967 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3968 if (!CompTy.isNull())
3969 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3970 break;
3971 case BinaryOperator::SubAssign:
3972 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3973 if (!CompTy.isNull())
3974 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3975 break;
3976 case BinaryOperator::ShlAssign:
3977 case BinaryOperator::ShrAssign:
3978 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3979 if (!CompTy.isNull())
3980 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3981 break;
3982 case BinaryOperator::AndAssign:
3983 case BinaryOperator::XorAssign:
3984 case BinaryOperator::OrAssign:
3985 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3986 if (!CompTy.isNull())
3987 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3988 break;
3989 case BinaryOperator::Comma:
3990 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3991 break;
3992 }
3993 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003994 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003995 if (CompTy.isNull())
3996 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3997 else
3998 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003999 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00004000}
4001
Reid Spencer5f016e22007-07-11 17:01:13 +00004002// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004003Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4004 tok::TokenKind Kind,
4005 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004006 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004007 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00004008
Steve Narofff69936d2007-09-16 03:34:24 +00004009 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4010 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004011
Douglas Gregor063daf62009-03-13 18:40:31 +00004012 if (getLangOptions().CPlusPlus &&
4013 (lhs->getType()->isOverloadableType() ||
4014 rhs->getType()->isOverloadableType())) {
4015 // Find all of the overloaded operators visible from this
4016 // point. We perform both an operator-name lookup from the local
4017 // scope and an argument-dependent lookup based on the types of
4018 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004019 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00004020 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4021 if (OverOp != OO_None) {
4022 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4023 Functions);
4024 Expr *Args[2] = { lhs, rhs };
4025 DeclarationName OpName
4026 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4027 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004028 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004029
Douglas Gregor063daf62009-03-13 18:40:31 +00004030 // Build the (potentially-overloaded, potentially-dependent)
4031 // binary operation.
4032 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004033 }
4034
Douglas Gregoreaebc752008-11-06 23:29:22 +00004035 // Build a built-in binary operation.
4036 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00004037}
4038
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004039Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4040 unsigned OpcIn,
4041 ExprArg InputArg) {
4042 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00004043
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004044 // FIXME: Input is modified below, but InputArg is not updated
4045 // appropriately.
4046 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00004047 QualType resultType;
4048 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004049 case UnaryOperator::PostInc:
4050 case UnaryOperator::PostDec:
4051 case UnaryOperator::OffsetOf:
4052 assert(false && "Invalid unary operator");
4053 break;
4054
Reid Spencer5f016e22007-07-11 17:01:13 +00004055 case UnaryOperator::PreInc:
4056 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004057 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4058 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004059 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004060 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00004061 resultType = CheckAddressOfOperand(Input, OpLoc);
4062 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004063 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00004064 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00004065 resultType = CheckIndirectionOperand(Input, OpLoc);
4066 break;
4067 case UnaryOperator::Plus:
4068 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004069 UsualUnaryConversions(Input);
4070 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004071 if (resultType->isDependentType())
4072 break;
Douglas Gregor74253732008-11-19 15:42:04 +00004073 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4074 break;
4075 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4076 resultType->isEnumeralType())
4077 break;
4078 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4079 Opc == UnaryOperator::Plus &&
4080 resultType->isPointerType())
4081 break;
4082
Sebastian Redl0eb23302009-01-19 00:08:26 +00004083 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4084 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004085 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004086 UsualUnaryConversions(Input);
4087 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004088 if (resultType->isDependentType())
4089 break;
Chris Lattner02a65142008-07-25 23:52:49 +00004090 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4091 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4092 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004093 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004094 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00004095 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004096 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4097 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004098 break;
4099 case UnaryOperator::LNot: // logical negation
4100 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004101 DefaultFunctionArrayConversion(Input);
4102 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004103 if (resultType->isDependentType())
4104 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004105 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00004106 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4107 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004108 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00004109 // In C++, it's bool. C++ 5.3.1p8
4110 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004111 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00004112 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00004113 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00004114 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00004115 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004116 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00004117 resultType = Input->getType();
4118 break;
4119 }
4120 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004121 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004122
4123 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004124 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004125}
4126
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004127// Unary Operators. 'Tok' is the token for the operator.
4128Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4129 tok::TokenKind Op, ExprArg input) {
4130 Expr *Input = (Expr*)input.get();
4131 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4132
4133 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4134 // Find all of the overloaded operators visible from this
4135 // point. We perform both an operator-name lookup from the local
4136 // scope and an argument-dependent lookup based on the types of
4137 // the arguments.
4138 FunctionSet Functions;
4139 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4140 if (OverOp != OO_None) {
4141 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4142 Functions);
4143 DeclarationName OpName
4144 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4145 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4146 }
4147
4148 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4149 }
4150
4151 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4152}
4153
Steve Naroff1b273c42007-09-16 14:56:35 +00004154/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00004155Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4156 SourceLocation LabLoc,
4157 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004158 // Look up the record for this label identifier.
Steve Naroffd8eb4562009-03-13 16:03:38 +00004159 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4160 LabelMap[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00004161
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00004162 // If we haven't seen this label yet, create a forward reference. It
4163 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00004164 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00004165 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004166
Reid Spencer5f016e22007-07-11 17:01:13 +00004167 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00004168 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4169 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00004170}
4171
Sebastian Redlf53597f2009-03-15 17:47:39 +00004172Sema::OwningExprResult
4173Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4174 SourceLocation RPLoc) { // "({..})"
4175 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004176 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4177 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4178
Eli Friedmandca2b732009-01-24 23:09:00 +00004179 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4180 if (isFileScope) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00004181 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00004182 }
4183
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004184 // FIXME: there are a variety of strange constraints to enforce here, for
4185 // example, it is not possible to goto into a stmt expression apparently.
4186 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004187
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004188 // FIXME: the last statement in the compount stmt has its value used. We
4189 // should not warn about it being unused.
4190
4191 // If there are sub stmts in the compound stmt, take the type of the last one
4192 // as the type of the stmtexpr.
4193 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004194
Chris Lattner611b2ec2008-07-26 19:51:01 +00004195 if (!Compound->body_empty()) {
4196 Stmt *LastStmt = Compound->body_back();
4197 // If LastStmt is a label, skip down through into the body.
4198 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4199 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004200
Chris Lattner611b2ec2008-07-26 19:51:01 +00004201 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004202 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004203 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004204
Sebastian Redlf53597f2009-03-15 17:47:39 +00004205 substmt.release();
4206 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004207}
Steve Naroffd34e9152007-08-01 22:05:33 +00004208
Sebastian Redlf53597f2009-03-15 17:47:39 +00004209Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4210 SourceLocation BuiltinLoc,
4211 SourceLocation TypeLoc,
4212 TypeTy *argty,
4213 OffsetOfComponent *CompPtr,
4214 unsigned NumComponents,
4215 SourceLocation RPLoc) {
4216 // FIXME: This function leaks all expressions in the offset components on
4217 // error.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004218 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4219 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004220
Sebastian Redl28507842009-02-26 14:39:58 +00004221 bool Dependent = ArgTy->isDependentType();
4222
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004223 // We must have at least one component that refers to the type, and the first
4224 // one is known to be a field designator. Verify that the ArgTy represents
4225 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00004226 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004227 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004228
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00004229 // FIXME: Does the type need to be complete?
4230
Eli Friedman35183ac2009-02-27 06:44:11 +00004231 // Otherwise, create a null pointer as the base, and iteratively process
4232 // the offsetof designators.
4233 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4234 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004235 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00004236 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004237
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004238 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4239 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00004240 // FIXME: This diagnostic isn't actually visible because the location is in
4241 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004242 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004243 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4244 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004245
Sebastian Redl28507842009-02-26 14:39:58 +00004246 if (!Dependent) {
4247 // FIXME: Dependent case loses a lot of information here. And probably
4248 // leaks like a sieve.
4249 for (unsigned i = 0; i != NumComponents; ++i) {
4250 const OffsetOfComponent &OC = CompPtr[i];
4251 if (OC.isBrackets) {
4252 // Offset of an array sub-field. TODO: Should we allow vector elements?
4253 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4254 if (!AT) {
4255 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004256 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4257 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004258 }
4259
4260 // FIXME: C++: Verify that operator[] isn't overloaded.
4261
Eli Friedman35183ac2009-02-27 06:44:11 +00004262 // Promote the array so it looks more like a normal array subscript
4263 // expression.
4264 DefaultFunctionArrayConversion(Res);
4265
Sebastian Redl28507842009-02-26 14:39:58 +00004266 // C99 6.5.2.1p1
4267 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004268 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00004269 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004270 return ExprError(Diag(Idx->getLocStart(),
4271 diag::err_typecheck_subscript)
4272 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00004273
4274 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4275 OC.LocEnd);
4276 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004277 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004278
Sebastian Redl28507842009-02-26 14:39:58 +00004279 const RecordType *RC = Res->getType()->getAsRecordType();
4280 if (!RC) {
4281 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004282 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4283 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004284 }
Chris Lattner704fe352007-08-30 17:59:59 +00004285
Sebastian Redl28507842009-02-26 14:39:58 +00004286 // Get the decl corresponding to this.
4287 RecordDecl *RD = RC->getDecl();
4288 FieldDecl *MemberDecl
4289 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4290 LookupMemberName)
4291 .getAsDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +00004292 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00004293 if (!MemberDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004294 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4295 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00004296
Sebastian Redl28507842009-02-26 14:39:58 +00004297 // FIXME: C++: Verify that MemberDecl isn't a static field.
4298 // FIXME: Verify that MemberDecl isn't a bitfield.
4299 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4300 // matter here.
4301 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004302 MemberDecl->getType().getNonReferenceType());
Sebastian Redl28507842009-02-26 14:39:58 +00004303 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004304 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004305
Sebastian Redlf53597f2009-03-15 17:47:39 +00004306 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4307 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004308}
4309
4310
Sebastian Redlf53597f2009-03-15 17:47:39 +00004311Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4312 TypeTy *arg1,TypeTy *arg2,
4313 SourceLocation RPLoc) {
Steve Naroffd34e9152007-08-01 22:05:33 +00004314 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4315 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004316
Steve Naroffd34e9152007-08-01 22:05:33 +00004317 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004318
Sebastian Redlf53597f2009-03-15 17:47:39 +00004319 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4320 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00004321}
4322
Sebastian Redlf53597f2009-03-15 17:47:39 +00004323Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4324 ExprArg cond,
4325 ExprArg expr1, ExprArg expr2,
4326 SourceLocation RPLoc) {
4327 Expr *CondExpr = static_cast<Expr*>(cond.get());
4328 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4329 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004330
Steve Naroffd04fdd52007-08-03 21:21:27 +00004331 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4332
Sebastian Redl28507842009-02-26 14:39:58 +00004333 QualType resType;
4334 if (CondExpr->isValueDependent()) {
4335 resType = Context.DependentTy;
4336 } else {
4337 // The conditional expression is required to be a constant expression.
4338 llvm::APSInt condEval(32);
4339 SourceLocation ExpLoc;
4340 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00004341 return ExprError(Diag(ExpLoc,
4342 diag::err_typecheck_choose_expr_requires_constant)
4343 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00004344
Sebastian Redl28507842009-02-26 14:39:58 +00004345 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4346 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4347 }
4348
Sebastian Redlf53597f2009-03-15 17:47:39 +00004349 cond.release(); expr1.release(); expr2.release();
4350 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4351 resType, RPLoc));
Steve Naroffd04fdd52007-08-03 21:21:27 +00004352}
4353
Steve Naroff4eb206b2008-09-03 18:15:37 +00004354//===----------------------------------------------------------------------===//
4355// Clang Extensions.
4356//===----------------------------------------------------------------------===//
4357
4358/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004359void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004360 // Analyze block parameters.
4361 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004362
Steve Naroff4eb206b2008-09-03 18:15:37 +00004363 // Add BSI to CurBlock.
4364 BSI->PrevBlockInfo = CurBlock;
4365 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004366
Steve Naroff4eb206b2008-09-03 18:15:37 +00004367 BSI->ReturnType = 0;
4368 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00004369 BSI->hasBlockDeclRefExprs = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004370
Steve Naroff090276f2008-10-10 01:28:17 +00004371 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004372 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004373}
4374
Mike Stump98eb8a72009-02-04 22:31:32 +00004375void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4376 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4377
4378 if (ParamInfo.getNumTypeObjects() == 0
4379 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4380 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4381
4382 // The type is entirely optional as well, if none, use DependentTy.
4383 if (T.isNull())
4384 T = Context.DependentTy;
4385
4386 // The parameter list is optional, if there was none, assume ().
4387 if (!T->isFunctionType())
4388 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4389
4390 CurBlock->hasPrototype = true;
4391 CurBlock->isVariadic = false;
4392 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4393 .getTypePtr();
4394
4395 if (!RetTy->isDependentType())
4396 CurBlock->ReturnType = RetTy;
4397 return;
4398 }
4399
Steve Naroff4eb206b2008-09-03 18:15:37 +00004400 // Analyze arguments to block.
4401 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4402 "Not a function declarator!");
4403 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004404
Steve Naroff090276f2008-10-10 01:28:17 +00004405 CurBlock->hasPrototype = FTI.hasPrototype;
4406 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004407
Steve Naroff4eb206b2008-09-03 18:15:37 +00004408 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4409 // no arguments, not a function that takes a single void argument.
4410 if (FTI.hasPrototype &&
4411 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4412 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4413 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4414 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004415 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004416 } else if (FTI.hasPrototype) {
4417 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004418 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4419 CurBlock->isVariadic = FTI.isVariadic;
Mike Stump98eb8a72009-02-04 22:31:32 +00004420 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4421
4422 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4423 .getTypePtr();
4424
4425 if (!RetTy->isDependentType())
4426 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004427 }
Steve Naroffe78b8092009-03-13 16:56:44 +00004428 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4429 CurBlock->Params.size());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004430
Steve Naroff090276f2008-10-10 01:28:17 +00004431 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4432 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4433 // If this has an identifier, add it to the scope stack.
4434 if ((*AI)->getIdentifier())
4435 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004436}
4437
4438/// ActOnBlockError - If there is an error parsing a block, this callback
4439/// is invoked to pop the information about the block from the action impl.
4440void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4441 // Ensure that CurBlock is deleted.
4442 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004443
Steve Naroff4eb206b2008-09-03 18:15:37 +00004444 // Pop off CurBlock, handle nested blocks.
4445 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004446
Steve Naroff4eb206b2008-09-03 18:15:37 +00004447 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregor4a471aa2009-03-11 23:54:15 +00004448
Steve Naroff4eb206b2008-09-03 18:15:37 +00004449}
4450
4451/// ActOnBlockStmtExpr - This is called when the body of a block statement
4452/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00004453Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4454 StmtArg body, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004455 // Ensure that CurBlock is deleted.
4456 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004457
Steve Naroff090276f2008-10-10 01:28:17 +00004458 PopDeclContext();
4459
Steve Naroff4eb206b2008-09-03 18:15:37 +00004460 // Pop off CurBlock, handle nested blocks.
4461 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004462
Steve Naroff4eb206b2008-09-03 18:15:37 +00004463 QualType RetTy = Context.VoidTy;
4464 if (BSI->ReturnType)
4465 RetTy = QualType(BSI->ReturnType, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004466
Steve Naroff4eb206b2008-09-03 18:15:37 +00004467 llvm::SmallVector<QualType, 8> ArgTypes;
4468 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4469 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004470
Steve Naroff4eb206b2008-09-03 18:15:37 +00004471 QualType BlockTy;
4472 if (!BSI->hasPrototype)
Douglas Gregor72564e72009-02-26 23:50:07 +00004473 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004474 else
4475 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004476 BSI->isVariadic, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004477
Steve Naroff4eb206b2008-09-03 18:15:37 +00004478 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004479
Sebastian Redlf53597f2009-03-15 17:47:39 +00004480 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4481 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4482 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00004483}
4484
Sebastian Redlf53597f2009-03-15 17:47:39 +00004485Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4486 ExprArg expr, TypeTy *type,
4487 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004488 QualType T = QualType::getFromOpaquePtr(type);
4489
4490 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004491
4492 // Get the va_list type
4493 QualType VaListType = Context.getBuiltinVaListType();
4494 // Deal with implicit array decay; for example, on x86-64,
4495 // va_list is an array, but it's supposed to decay to
4496 // a pointer for va_arg.
4497 if (VaListType->isArrayType())
4498 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004499 // Make sure the input expression also decays appropriately.
Sebastian Redlf53597f2009-03-15 17:47:39 +00004500 Expr *E = static_cast<Expr*>(expr.get());
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004501 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004502
4503 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004504 return ExprError(Diag(E->getLocStart(),
4505 diag::err_first_argument_to_va_arg_not_of_type_va_list)
4506 << E->getType() << E->getSourceRange());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004507
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004508 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004509
Sebastian Redlf53597f2009-03-15 17:47:39 +00004510 expr.release();
4511 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4512 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004513}
4514
Sebastian Redlf53597f2009-03-15 17:47:39 +00004515Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004516 // The type of __null will be int or long, depending on the size of
4517 // pointers on the target.
4518 QualType Ty;
4519 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4520 Ty = Context.IntTy;
4521 else
4522 Ty = Context.LongTy;
4523
Sebastian Redlf53597f2009-03-15 17:47:39 +00004524 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004525}
4526
Chris Lattner5cf216b2008-01-04 18:04:52 +00004527bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4528 SourceLocation Loc,
4529 QualType DstType, QualType SrcType,
4530 Expr *SrcExpr, const char *Flavor) {
4531 // Decode the result (notice that AST's are still created for extensions).
4532 bool isInvalid = false;
4533 unsigned DiagKind;
4534 switch (ConvTy) {
4535 default: assert(0 && "Unknown conversion type");
4536 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004537 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004538 DiagKind = diag::ext_typecheck_convert_pointer_int;
4539 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004540 case IntToPointer:
4541 DiagKind = diag::ext_typecheck_convert_int_pointer;
4542 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004543 case IncompatiblePointer:
4544 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4545 break;
4546 case FunctionVoidPointer:
4547 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4548 break;
4549 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004550 // If the qualifiers lost were because we were applying the
4551 // (deprecated) C++ conversion from a string literal to a char*
4552 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4553 // Ideally, this check would be performed in
4554 // CheckPointerTypesForAssignment. However, that would require a
4555 // bit of refactoring (so that the second argument is an
4556 // expression, rather than a type), which should be done as part
4557 // of a larger effort to fix CheckPointerTypesForAssignment for
4558 // C++ semantics.
4559 if (getLangOptions().CPlusPlus &&
4560 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4561 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004562 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4563 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004564 case IntToBlockPointer:
4565 DiagKind = diag::err_int_to_block_pointer;
4566 break;
4567 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004568 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004569 break;
Steve Naroff39579072008-10-14 22:18:38 +00004570 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00004571 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00004572 // it can give a more specific diagnostic.
4573 DiagKind = diag::warn_incompatible_qualified_id;
4574 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004575 case IncompatibleVectors:
4576 DiagKind = diag::warn_incompatible_vectors;
4577 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004578 case Incompatible:
4579 DiagKind = diag::err_typecheck_convert_incompatible;
4580 isInvalid = true;
4581 break;
4582 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004583
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004584 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4585 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004586 return isInvalid;
4587}
Anders Carlssone21555e2008-11-30 19:50:32 +00004588
4589bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4590{
4591 Expr::EvalResult EvalResult;
4592
Mike Stumpeed9cac2009-02-19 03:04:26 +00004593 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00004594 EvalResult.HasSideEffects) {
4595 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4596
4597 if (EvalResult.Diag) {
4598 // We only show the note if it's not the usual "invalid subexpression"
4599 // or if it's actually in a subexpression.
4600 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4601 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4602 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4603 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004604
Anders Carlssone21555e2008-11-30 19:50:32 +00004605 return true;
4606 }
4607
4608 if (EvalResult.Diag) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004609 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssone21555e2008-11-30 19:50:32 +00004610 E->getSourceRange();
4611
4612 // Print the reason it's not a constant.
4613 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4614 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4615 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004616
Anders Carlssone21555e2008-11-30 19:50:32 +00004617 if (Result)
4618 *Result = EvalResult.Val.getInt();
4619 return false;
4620}