blob: 98d6b12b9c4a0ace84c5936b45ce56cb3efea5af [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Douglas Gregoraa57e862009-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 Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-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 Lattnerfb1bb822009-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 Lattner2cb744b2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregoraa57e862009-02-18 21:56:37 +000072 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-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 Gregor6f8c3682009-02-24 04:26:15 +000079 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
82 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregor6f8c3682009-02-24 04:26:15 +000087 if (D->getDeclContext()->isFunctionOrMethod() &&
88 !D->getDeclContext()->Encloses(CurContext)) {
89 // We've found the name of a function or variable that was
90 // declared with external linkage within another function (and,
91 // therefore, a scope where we wouldn't normally see the
92 // declaration). Once we've made sure that no previous declaration
93 // was properly made visible, produce a warning.
94 bool HasGlobalScopedDeclaration = false;
95 for (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); FD;
96 FD = FD->getPreviousDeclaration()) {
97 if (FD->getDeclContext()->isFileContext()) {
98 HasGlobalScopedDeclaration = true;
99 break;
100 }
101 }
102 // FIXME: do the same thing for variable declarations
103
104 if (!HasGlobalScopedDeclaration) {
105 Diag(Loc, diag::warn_use_out_of_scope_declaration) << D;
106 Diag(D->getLocation(), diag::note_previous_declaration);
107 }
108 }
Douglas Gregoraa57e862009-02-18 21:56:37 +0000109
110 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000111}
112
Chris Lattner299b8842008-07-25 21:10:04 +0000113//===----------------------------------------------------------------------===//
114// Standard Promotions and Conversions
115//===----------------------------------------------------------------------===//
116
Chris Lattner299b8842008-07-25 21:10:04 +0000117/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
118void Sema::DefaultFunctionArrayConversion(Expr *&E) {
119 QualType Ty = E->getType();
120 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
121
Chris Lattner299b8842008-07-25 21:10:04 +0000122 if (Ty->isFunctionType())
123 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000124 else if (Ty->isArrayType()) {
125 // In C90 mode, arrays only promote to pointers if the array expression is
126 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
127 // type 'array of type' is converted to an expression that has type 'pointer
128 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
129 // that has type 'array of type' ...". The relevant change is "an lvalue"
130 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000131 //
132 // C++ 4.2p1:
133 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
134 // T" can be converted to an rvalue of type "pointer to T".
135 //
136 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
137 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000138 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
139 }
Chris Lattner299b8842008-07-25 21:10:04 +0000140}
141
142/// UsualUnaryConversions - Performs various conversions that are common to most
143/// operators (C99 6.3). The conversions of array and function types are
144/// sometimes surpressed. For example, the array->pointer conversion doesn't
145/// apply if the array is an argument to the sizeof or address (&) operators.
146/// In these instances, this routine should *not* be called.
147Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
148 QualType Ty = Expr->getType();
149 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
150
Chris Lattner299b8842008-07-25 21:10:04 +0000151 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
152 ImpCastExprToType(Expr, Context.IntTy);
153 else
154 DefaultFunctionArrayConversion(Expr);
155
156 return Expr;
157}
158
Chris Lattner9305c3d2008-07-25 22:25:12 +0000159/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
160/// do not have a prototype. Arguments that have type float are promoted to
161/// double. All other argument types are converted by UsualUnaryConversions().
162void Sema::DefaultArgumentPromotion(Expr *&Expr) {
163 QualType Ty = Expr->getType();
164 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
165
166 // If this is a 'float' (CVR qualified or typedef) promote to double.
167 if (const BuiltinType *BT = Ty->getAsBuiltinType())
168 if (BT->getKind() == BuiltinType::Float)
169 return ImpCastExprToType(Expr, Context.DoubleTy);
170
171 UsualUnaryConversions(Expr);
172}
173
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000174// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
175// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000176void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000177 DefaultArgumentPromotion(Expr);
178
179 if (!Expr->getType()->isPODType()) {
180 Diag(Expr->getLocStart(),
181 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
182 Expr->getType() << CT;
183 }
184}
185
186
Chris Lattner299b8842008-07-25 21:10:04 +0000187/// UsualArithmeticConversions - Performs various conversions that are common to
188/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
189/// routine returns the first non-arithmetic type found. The client is
190/// responsible for emitting appropriate error diagnostics.
191/// FIXME: verify the conversion rules for "complex int" are consistent with
192/// GCC.
193QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
194 bool isCompAssign) {
195 if (!isCompAssign) {
196 UsualUnaryConversions(lhsExpr);
197 UsualUnaryConversions(rhsExpr);
198 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000199
Chris Lattner299b8842008-07-25 21:10:04 +0000200 // For conversion purposes, we ignore any qualifiers.
201 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000202 QualType lhs =
203 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
204 QualType rhs =
205 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000206
207 // If both types are identical, no conversion is needed.
208 if (lhs == rhs)
209 return lhs;
210
211 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
212 // The caller can deal with this (e.g. pointer + int).
213 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
214 return lhs;
215
216 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
217 if (!isCompAssign) {
218 ImpCastExprToType(lhsExpr, destType);
219 ImpCastExprToType(rhsExpr, destType);
220 }
221 return destType;
222}
223
224QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
225 // Perform the usual unary conversions. We do this early so that
226 // integral promotions to "int" can allow us to exit early, in the
227 // lhs == rhs check. Also, for conversion purposes, we ignore any
228 // qualifiers. For example, "const float" and "float" are
229 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000230 if (lhs->isPromotableIntegerType())
231 lhs = Context.IntTy;
232 else
233 lhs = lhs.getUnqualifiedType();
234 if (rhs->isPromotableIntegerType())
235 rhs = Context.IntTy;
236 else
237 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000238
Chris Lattner299b8842008-07-25 21:10:04 +0000239 // If both types are identical, no conversion is needed.
240 if (lhs == rhs)
241 return lhs;
242
243 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
244 // The caller can deal with this (e.g. pointer + int).
245 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
246 return lhs;
247
248 // At this point, we have two different arithmetic types.
249
250 // Handle complex types first (C99 6.3.1.8p1).
251 if (lhs->isComplexType() || rhs->isComplexType()) {
252 // if we have an integer operand, the result is the complex type.
253 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
254 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000255 return lhs;
256 }
257 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
258 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000259 return rhs;
260 }
261 // This handles complex/complex, complex/float, or float/complex.
262 // When both operands are complex, the shorter operand is converted to the
263 // type of the longer, and that is the type of the result. This corresponds
264 // to what is done when combining two real floating-point operands.
265 // The fun begins when size promotion occur across type domains.
266 // From H&S 6.3.4: When one operand is complex and the other is a real
267 // floating-point type, the less precise type is converted, within it's
268 // real or complex domain, to the precision of the other type. For example,
269 // when combining a "long double" with a "double _Complex", the
270 // "double _Complex" is promoted to "long double _Complex".
271 int result = Context.getFloatingTypeOrder(lhs, rhs);
272
273 if (result > 0) { // The left side is bigger, convert rhs.
274 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000275 } else if (result < 0) { // The right side is bigger, convert lhs.
276 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000277 }
278 // At this point, lhs and rhs have the same rank/size. Now, make sure the
279 // domains match. This is a requirement for our implementation, C99
280 // does not require this promotion.
281 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
282 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000283 return rhs;
284 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000285 return lhs;
286 }
287 }
288 return lhs; // The domain/size match exactly.
289 }
290 // Now handle "real" floating types (i.e. float, double, long double).
291 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
292 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000293 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000294 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return lhs;
296 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000297 if (rhs->isComplexIntegerType()) {
298 // convert rhs to the complex floating point type.
299 return Context.getComplexType(lhs);
300 }
301 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000302 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000303 return rhs;
304 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000305 if (lhs->isComplexIntegerType()) {
306 // convert lhs to the complex floating point type.
307 return Context.getComplexType(rhs);
308 }
Chris Lattner299b8842008-07-25 21:10:04 +0000309 // We have two real floating types, float/complex combos were handled above.
310 // Convert the smaller operand to the bigger result.
311 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000312 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000313 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000314 assert(result < 0 && "illegal float comparison");
315 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000316 }
317 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
318 // Handle GCC complex int extension.
319 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
320 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
321
322 if (lhsComplexInt && rhsComplexInt) {
323 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000324 rhsComplexInt->getElementType()) >= 0)
325 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000326 return rhs;
327 } else if (lhsComplexInt && rhs->isIntegerType()) {
328 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000329 return lhs;
330 } else if (rhsComplexInt && lhs->isIntegerType()) {
331 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000332 return rhs;
333 }
334 }
335 // Finally, we have two differing integer types.
336 // The rules for this case are in C99 6.3.1.8
337 int compare = Context.getIntegerTypeOrder(lhs, rhs);
338 bool lhsSigned = lhs->isSignedIntegerType(),
339 rhsSigned = rhs->isSignedIntegerType();
340 QualType destType;
341 if (lhsSigned == rhsSigned) {
342 // Same signedness; use the higher-ranked type
343 destType = compare >= 0 ? lhs : rhs;
344 } else if (compare != (lhsSigned ? 1 : -1)) {
345 // The unsigned type has greater than or equal rank to the
346 // signed type, so use the unsigned type
347 destType = lhsSigned ? rhs : lhs;
348 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
349 // The two types are different widths; if we are here, that
350 // means the signed type is larger than the unsigned type, so
351 // use the signed type.
352 destType = lhsSigned ? lhs : rhs;
353 } else {
354 // The signed type is higher-ranked than the unsigned type,
355 // but isn't actually any bigger (like unsigned int and long
356 // on most 32-bit systems). Use the unsigned type corresponding
357 // to the signed type.
358 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
359 }
Chris Lattner299b8842008-07-25 21:10:04 +0000360 return destType;
361}
362
363//===----------------------------------------------------------------------===//
364// Semantic Analysis for various Expression Types
365//===----------------------------------------------------------------------===//
366
367
Steve Naroff87d58b42007-09-16 03:34:24 +0000368/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000369/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
370/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
371/// multiple tokens. However, the common case is that StringToks points to one
372/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000373///
374Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000375Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000376 assert(NumStringToks && "Must have at least one string!");
377
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000378 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000379 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000380 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000381
382 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
383 for (unsigned i = 0; i != NumStringToks; ++i)
384 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000385
Chris Lattnera6dcce32008-02-11 00:02:17 +0000386 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000387 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000388 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000389
390 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
391 if (getLangOptions().CPlusPlus)
392 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000393
Chris Lattnera6dcce32008-02-11 00:02:17 +0000394 // Get an array type for the string, according to C99 6.4.5. This includes
395 // the nul terminator character as well as the string length for pascal
396 // strings.
397 StrTy = Context.getConstantArrayType(StrTy,
398 llvm::APInt(32, Literal.GetStringLength()+1),
399 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000400
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000402 return Owned(StringLiteral::Create(Context, Literal.GetString(),
403 Literal.GetStringLength(),
404 Literal.AnyWide, StrTy,
405 &StringTokLocs[0],
406 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000407}
408
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000409/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
410/// CurBlock to VD should cause it to be snapshotted (as we do for auto
411/// variables defined outside the block) or false if this is not needed (e.g.
412/// for values inside the block or for globals).
413///
414/// FIXME: This will create BlockDeclRefExprs for global variables,
415/// function references, etc which is suboptimal :) and breaks
416/// things like "integer constant expression" tests.
417static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
418 ValueDecl *VD) {
419 // If the value is defined inside the block, we couldn't snapshot it even if
420 // we wanted to.
421 if (CurBlock->TheDecl == VD->getDeclContext())
422 return false;
423
424 // If this is an enum constant or function, it is constant, don't snapshot.
425 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
426 return false;
427
428 // If this is a reference to an extern, static, or global variable, no need to
429 // snapshot it.
430 // FIXME: What about 'const' variables in C++?
431 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
432 return Var->hasLocalStorage();
433
434 return true;
435}
436
437
438
Steve Naroff0acc9c92007-09-15 18:49:24 +0000439/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000440/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000441/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000442/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000443/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000444Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
445 IdentifierInfo &II,
446 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000447 const CXXScopeSpec *SS,
448 bool isAddressOfOperand) {
449 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000450 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000451}
452
Douglas Gregor566782a2009-01-06 05:10:23 +0000453/// BuildDeclRefExpr - Build either a DeclRefExpr or a
454/// QualifiedDeclRefExpr based on whether or not SS is a
455/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000456DeclRefExpr *
457Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
458 bool TypeDependent, bool ValueDependent,
459 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000460 if (SS && !SS->isEmpty())
461 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stump9afab102009-02-19 03:04:26 +0000462 ValueDependent,
463 SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000464 else
465 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000466}
467
Douglas Gregor723d3332009-01-07 00:43:41 +0000468/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
469/// variable corresponding to the anonymous union or struct whose type
470/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000471static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000472 assert(Record->isAnonymousStructOrUnion() &&
473 "Record must be an anonymous struct or union!");
474
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000475 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000476 // be an O(1) operation rather than a slow walk through DeclContext's
477 // vector (which itself will be eliminated). DeclGroups might make
478 // this even better.
479 DeclContext *Ctx = Record->getDeclContext();
480 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
481 DEnd = Ctx->decls_end();
482 D != DEnd; ++D) {
483 if (*D == Record) {
484 // The object for the anonymous struct/union directly
485 // follows its type in the list of declarations.
486 ++D;
487 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000488 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000489 return *D;
490 }
491 }
492
493 assert(false && "Missing object for anonymous record");
494 return 0;
495}
496
Sebastian Redlcd883f72009-01-18 18:53:16 +0000497Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000498Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
499 FieldDecl *Field,
500 Expr *BaseObjectExpr,
501 SourceLocation OpLoc) {
502 assert(Field->getDeclContext()->isRecord() &&
503 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
504 && "Field must be stored inside an anonymous struct or union");
505
506 // Construct the sequence of field member references
507 // we'll have to perform to get to the field in the anonymous
508 // union/struct. The list of members is built from the field
509 // outward, so traverse it backwards to go from an object in
510 // the current context to the field we found.
511 llvm::SmallVector<FieldDecl *, 4> AnonFields;
512 AnonFields.push_back(Field);
513 VarDecl *BaseObject = 0;
514 DeclContext *Ctx = Field->getDeclContext();
515 do {
516 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000517 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000518 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
519 AnonFields.push_back(AnonField);
520 else {
521 BaseObject = cast<VarDecl>(AnonObject);
522 break;
523 }
524 Ctx = Ctx->getParent();
525 } while (Ctx->isRecord() &&
526 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
527
528 // Build the expression that refers to the base object, from
529 // which we will build a sequence of member references to each
530 // of the anonymous union objects and, eventually, the field we
531 // found via name lookup.
532 bool BaseObjectIsPointer = false;
533 unsigned ExtraQuals = 0;
534 if (BaseObject) {
535 // BaseObject is an anonymous struct/union variable (and is,
536 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000539 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000540 ExtraQuals
541 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
547 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
550 }
551 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
552 } else {
553 // We've found a member of an anonymous struct/union that is
554 // inside a non-anonymous struct/union, so in a well-formed
555 // program our base object expression is "this".
556 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
557 if (!MD->isStatic()) {
558 QualType AnonFieldType
559 = Context.getTagDeclType(
560 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
561 QualType ThisType = Context.getTagDeclType(MD->getParent());
562 if ((Context.getCanonicalType(AnonFieldType)
563 == Context.getCanonicalType(ThisType)) ||
564 IsDerivedFrom(ThisType, AnonFieldType)) {
565 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000566 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000567 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000568 BaseObjectIsPointer = true;
569 }
570 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000571 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
572 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000573 }
574 ExtraQuals = MD->getTypeQualifiers();
575 }
576
577 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000578 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
579 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000580 }
581
582 // Build the implicit member references to the field of the
583 // anonymous struct/union.
584 Expr *Result = BaseObjectExpr;
585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
589 if (!(*FI)->isMutable()) {
590 unsigned combinedQualifiers
591 = MemberType.getCVRQualifiers() | ExtraQuals;
592 MemberType = MemberType.getQualifiedType(combinedQualifiers);
593 }
Steve Naroff774e4152009-01-21 00:14:39 +0000594 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
595 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000596 BaseObjectIsPointer = false;
597 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
598 OpLoc = SourceLocation();
599 }
600
Sebastian Redlcd883f72009-01-18 18:53:16 +0000601 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000602}
603
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000604/// ActOnDeclarationNameExpr - The parser has read some kind of name
605/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
606/// performs lookup on that name and returns an expression that refers
607/// to that name. This routine isn't directly called from the parser,
608/// because the parser doesn't know about DeclarationName. Rather,
609/// this routine is called by ActOnIdentifierExpr,
610/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
611/// which form the DeclarationName from the corresponding syntactic
612/// forms.
613///
614/// HasTrailingLParen indicates whether this identifier is used in a
615/// function call context. LookupCtx is only used for a C++
616/// qualified-id (foo::bar) to indicate the class or namespace that
617/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000618///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000619/// isAddressOfOperand means that this expression is the direct operand
620/// of an address-of operator. This matters because this is the only
621/// situation where a qualified name referencing a non-static member may
622/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623Sema::OwningExprResult
624Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
625 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000626 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000627 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000628 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000629 if (SS && SS->isInvalid())
630 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000631 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
632 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000633
Douglas Gregor09be81b2009-02-04 17:27:36 +0000634 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000635 if (Lookup.isAmbiguous()) {
636 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
637 SS && SS->isSet() ? SS->getRange()
638 : SourceRange());
639 return ExprError();
640 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000641 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000642
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000643 // If this reference is in an Objective-C method, then ivar lookup happens as
644 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000645 IdentifierInfo *II = Name.getAsIdentifierInfo();
646 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000647 // There are two cases to handle here. 1) scoped lookup could have failed,
648 // in which case we should look for an ivar. 2) scoped lookup could have
649 // found a decl, but that decl is outside the current method (i.e. a global
650 // variable). In these two cases, we do a lookup for an ivar with this
651 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000652 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000653 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000654 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000655 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000656 if (DiagnoseUseOfDecl(IV, Loc))
657 return ExprError();
Chris Lattner2a3bef92009-02-16 17:19:12 +0000658
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000659 // FIXME: This should use a new expr for a direct reference, don't turn
660 // this into Self->ivar, just return a BareIVarExpr or something.
661 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000662 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Mike Stump9afab102009-02-19 03:04:26 +0000663 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +0000664 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000665 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000666 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000667 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000668 }
669 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000670 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000671 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000672 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000673 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000674 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000675 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000676 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000677
Douglas Gregoraa57e862009-02-18 21:56:37 +0000678 // Determine whether this name might be a candidate for
679 // argument-dependent lookup.
680 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
681 HasTrailingLParen;
682
683 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000684 // We've seen something of the form
685 //
686 // identifier(
687 //
688 // and we did not find any entity by the name
689 // "identifier". However, this identifier is still subject to
690 // argument-dependent lookup, so keep track of the name.
691 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
692 Context.OverloadTy,
693 Loc));
694 }
695
Chris Lattner4b009652007-07-25 00:24:17 +0000696 if (D == 0) {
697 // Otherwise, this could be an implicitly declared function reference (legal
698 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000699 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000700 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000701 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000702 else {
703 // If this name wasn't predeclared and if this is not a function call,
704 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000705 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000706 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
707 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000708 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
709 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_undeclared_use)
711 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000712 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000713 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000714 }
715 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000716
Sebastian Redl0c9da212009-02-03 20:19:35 +0000717 // If this is an expression of the form &Class::member, don't build an
718 // implicit member ref, because we want a pointer to the member in general,
719 // not any specific instance's member.
720 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000721 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000722 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000723 QualType DType;
724 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
725 DType = FD->getType().getNonReferenceType();
726 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
727 DType = Method->getType();
728 } else if (isa<OverloadedFunctionDecl>(D)) {
729 DType = Context.OverloadTy;
730 }
731 // Could be an inner type. That's diagnosed below, so ignore it here.
732 if (!DType.isNull()) {
733 // The pointer is type- and value-dependent if it points into something
734 // dependent.
735 bool Dependent = false;
736 for (; DC; DC = DC->getParent()) {
737 // FIXME: could stop early at namespace scope.
738 if (DC->isRecord()) {
739 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
740 if (Context.getTypeDeclType(Record)->isDependentType()) {
741 Dependent = true;
742 break;
743 }
744 }
745 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000746 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000747 }
748 }
749 }
750
Douglas Gregor723d3332009-01-07 00:43:41 +0000751 // We may have found a field within an anonymous union or struct
752 // (C++ [class.union]).
753 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
754 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
755 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000756
Douglas Gregor3257fb52008-12-22 05:46:06 +0000757 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
758 if (!MD->isStatic()) {
759 // C++ [class.mfct.nonstatic]p2:
760 // [...] if name lookup (3.4.1) resolves the name in the
761 // id-expression to a nonstatic nontype member of class X or of
762 // a base class of X, the id-expression is transformed into a
763 // class member access expression (5.2.5) using (*this) (9.3.2)
764 // as the postfix-expression to the left of the '.' operator.
765 DeclContext *Ctx = 0;
766 QualType MemberType;
767 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
768 Ctx = FD->getDeclContext();
769 MemberType = FD->getType();
770
771 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
772 MemberType = RefType->getPointeeType();
773 else if (!FD->isMutable()) {
774 unsigned combinedQualifiers
775 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
776 MemberType = MemberType.getQualifiedType(combinedQualifiers);
777 }
778 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
779 if (!Method->isStatic()) {
780 Ctx = Method->getParent();
781 MemberType = Method->getType();
782 }
783 } else if (OverloadedFunctionDecl *Ovl
784 = dyn_cast<OverloadedFunctionDecl>(D)) {
785 for (OverloadedFunctionDecl::function_iterator
786 Func = Ovl->function_begin(),
787 FuncEnd = Ovl->function_end();
788 Func != FuncEnd; ++Func) {
789 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
790 if (!DMethod->isStatic()) {
791 Ctx = Ovl->getDeclContext();
792 MemberType = Context.OverloadTy;
793 break;
794 }
795 }
796 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000797
798 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000799 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
800 QualType ThisType = Context.getTagDeclType(MD->getParent());
801 if ((Context.getCanonicalType(CtxType)
802 == Context.getCanonicalType(ThisType)) ||
803 IsDerivedFrom(ThisType, CtxType)) {
804 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000805 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000806 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000807 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000808 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000809 }
810 }
811 }
812 }
813
Douglas Gregor8acb7272008-12-11 16:49:14 +0000814 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000815 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
816 if (MD->isStatic())
817 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000818 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
819 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000820 }
821
Douglas Gregor3257fb52008-12-22 05:46:06 +0000822 // Any other ways we could have found the field in a well-formed
823 // program would have been turned into implicit member expressions
824 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000825 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
826 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000827 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000828
Chris Lattner4b009652007-07-25 00:24:17 +0000829 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000830 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000831 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000832 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000833 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000834 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000835
Steve Naroffd6163f32008-09-05 22:11:13 +0000836 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000837 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000838 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
839 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000840 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
841 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
842 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000843 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000844
Douglas Gregoraa57e862009-02-18 21:56:37 +0000845 // Check whether this declaration can be used. Note that we suppress
846 // this check when we're going to perform argument-dependent lookup
847 // on this function name, because this might not be the function
848 // that overload resolution actually selects.
849 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
850 return ExprError();
851
Douglas Gregor48840c72008-12-10 23:01:14 +0000852 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000853 // Warn about constructs like:
854 // if (void *X = foo()) { ... } else { X }.
855 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000856 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
857 Scope *CheckS = S;
858 while (CheckS) {
859 if (CheckS->isWithinElse() &&
860 CheckS->getControlParent()->isDeclScope(Var)) {
861 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000862 ExprError(Diag(Loc, diag::warn_value_always_false)
863 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000864 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000865 ExprError(Diag(Loc, diag::warn_value_always_zero)
866 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000867 break;
868 }
869
870 // Move up one more control parent to check again.
871 CheckS = CheckS->getControlParent();
872 if (CheckS)
873 CheckS = CheckS->getParent();
874 }
875 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000876 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
877 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
878 // C99 DR 316 says that, if a function type comes from a
879 // function definition (without a prototype), that type is only
880 // used for checking compatibility. Therefore, when referencing
881 // the function, we pretend that we don't have the full function
882 // type.
883 QualType T = Func->getType();
884 QualType NoProtoType = T;
885 if (const FunctionTypeProto *Proto = T->getAsFunctionTypeProto())
886 NoProtoType = Context.getFunctionTypeNoProto(Proto->getResultType());
887 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
888 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000889 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000890
891 // Only create DeclRefExpr's for valid Decl's.
892 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000893 return ExprError();
894
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000895 // If the identifier reference is inside a block, and it refers to a value
896 // that is outside the block, create a BlockDeclRefExpr instead of a
897 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
898 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000899 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000900 // We do not do this for things like enum constants, global variables, etc,
901 // as they do not get snapshotted.
902 //
903 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000904 // Blocks that have these can't be constant.
905 CurBlock->hasBlockDeclRefExprs = true;
906
Steve Naroff52059382008-10-10 01:28:17 +0000907 // The BlocksAttr indicates the variable is bound by-reference.
908 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000909 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000910 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000911
Steve Naroff52059382008-10-10 01:28:17 +0000912 // Variable will be bound by-copy, make it const within the closure.
913 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000914 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000915 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000916 }
917 // If this reference is not in a block or if the referenced variable is
918 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000919
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000920 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000921 bool ValueDependent = false;
922 if (getLangOptions().CPlusPlus) {
923 // C++ [temp.dep.expr]p3:
924 // An id-expression is type-dependent if it contains:
925 // - an identifier that was declared with a dependent type,
926 if (VD->getType()->isDependentType())
927 TypeDependent = true;
928 // - FIXME: a template-id that is dependent,
929 // - a conversion-function-id that specifies a dependent type,
930 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
931 Name.getCXXNameType()->isDependentType())
932 TypeDependent = true;
933 // - a nested-name-specifier that contains a class-name that
934 // names a dependent type.
935 else if (SS && !SS->isEmpty()) {
936 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
937 DC; DC = DC->getParent()) {
938 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000939 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000940 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
941 if (Context.getTypeDeclType(Record)->isDependentType()) {
942 TypeDependent = true;
943 break;
944 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000945 }
946 }
947 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000948
Douglas Gregora5d84612008-12-10 20:57:37 +0000949 // C++ [temp.dep.constexpr]p2:
950 //
951 // An identifier is value-dependent if it is:
952 // - a name declared with a dependent type,
953 if (TypeDependent)
954 ValueDependent = true;
955 // - the name of a non-type template parameter,
956 else if (isa<NonTypeTemplateParmDecl>(VD))
957 ValueDependent = true;
958 // - a constant with integral or enumeration type and is
959 // initialized with an expression that is value-dependent
960 // (FIXME!).
961 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000962
Sebastian Redlcd883f72009-01-18 18:53:16 +0000963 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
964 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000965}
966
Sebastian Redlcd883f72009-01-18 18:53:16 +0000967Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
968 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000969 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000970
Chris Lattner4b009652007-07-25 00:24:17 +0000971 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000972 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000973 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
974 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
975 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000976 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000977
Chris Lattner7e637512008-01-12 08:14:25 +0000978 // Pre-defined identifiers are of type char[x], where x is the length of the
979 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000980 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000981 if (FunctionDecl *FD = getCurFunctionDecl())
982 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000983 else if (ObjCMethodDecl *MD = getCurMethodDecl())
984 Length = MD->getSynthesizedMethodSize();
985 else {
986 Diag(Loc, diag::ext_predef_outside_function);
987 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
988 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
989 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
991
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000992 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000993 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000994 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000995 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000996}
997
Sebastian Redlcd883f72009-01-18 18:53:16 +0000998Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000999 llvm::SmallString<16> CharBuffer;
1000 CharBuffer.resize(Tok.getLength());
1001 const char *ThisTokBegin = &CharBuffer[0];
1002 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001003
Chris Lattner4b009652007-07-25 00:24:17 +00001004 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1005 Tok.getLocation(), PP);
1006 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001007 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001008
1009 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1010
Sebastian Redl75324932009-01-20 22:23:13 +00001011 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1012 Literal.isWide(),
1013 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001014}
1015
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1017 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1019 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001020 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001021 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001022 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001023 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001024 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001025
Chris Lattner4b009652007-07-25 00:24:17 +00001026 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001027 // Add padding so that NumericLiteralParser can overread by one character.
1028 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001029 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 // Get the spelling of the token, which eliminates trigraphs, etc.
1032 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033
Chris Lattner4b009652007-07-25 00:24:17 +00001034 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1035 Tok.getLocation(), PP);
1036 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001037 return ExprError();
1038
Chris Lattner1de66eb2007-08-26 03:42:43 +00001039 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040
Chris Lattner1de66eb2007-08-26 03:42:43 +00001041 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001042 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001043 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001044 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001045 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001046 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001047 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001048 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001049
1050 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1051
Ted Kremenekddedbe22007-11-29 00:56:49 +00001052 // isExact will be set by GetFloatValue().
1053 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001054 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1055 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001056
Chris Lattner1de66eb2007-08-26 03:42:43 +00001057 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001058 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001059 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001060 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001061
Neil Booth7421e9c2007-08-29 22:00:19 +00001062 // long long is a C99 feature.
1063 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001064 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001065 Diag(Tok.getLocation(), diag::ext_longlong);
1066
Chris Lattner4b009652007-07-25 00:24:17 +00001067 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001068 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001069
Chris Lattner4b009652007-07-25 00:24:17 +00001070 if (Literal.GetIntegerValue(ResultVal)) {
1071 // If this value didn't fit into uintmax_t, warn and force to ull.
1072 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001073 Ty = Context.UnsignedLongLongTy;
1074 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001075 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001076 } else {
1077 // If this value fits into a ULL, try to figure out what else it fits into
1078 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001079
Chris Lattner4b009652007-07-25 00:24:17 +00001080 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1081 // be an unsigned int.
1082 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1083
1084 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001085 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001086 if (!Literal.isLong && !Literal.isLongLong) {
1087 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001088 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001089
Chris Lattner4b009652007-07-25 00:24:17 +00001090 // Does it fit in a unsigned int?
1091 if (ResultVal.isIntN(IntSize)) {
1092 // Does it fit in a signed int?
1093 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001094 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001095 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001096 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001097 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001098 }
Chris Lattner4b009652007-07-25 00:24:17 +00001099 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001100
Chris Lattner4b009652007-07-25 00:24:17 +00001101 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001102 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001103 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001104
Chris Lattner4b009652007-07-25 00:24:17 +00001105 // Does it fit in a unsigned long?
1106 if (ResultVal.isIntN(LongSize)) {
1107 // Does it fit in a signed long?
1108 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001109 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001110 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001111 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001112 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001113 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001114 }
1115
Chris Lattner4b009652007-07-25 00:24:17 +00001116 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001117 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001118 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001119
Chris Lattner4b009652007-07-25 00:24:17 +00001120 // Does it fit in a unsigned long long?
1121 if (ResultVal.isIntN(LongLongSize)) {
1122 // Does it fit in a signed long long?
1123 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001124 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001125 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001126 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001127 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001128 }
1129 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001130
Chris Lattner4b009652007-07-25 00:24:17 +00001131 // If we still couldn't decide a type, we probably have something that
1132 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001133 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001134 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001135 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001136 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001138
Chris Lattnere4068872008-05-09 05:59:00 +00001139 if (ResultVal.getBitWidth() != Width)
1140 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001141 }
Sebastian Redl75324932009-01-20 22:23:13 +00001142 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001143 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001144
Chris Lattner1de66eb2007-08-26 03:42:43 +00001145 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1146 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001147 Res = new (Context) ImaginaryLiteral(Res,
1148 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001149
1150 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001151}
1152
Sebastian Redlcd883f72009-01-18 18:53:16 +00001153Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1154 SourceLocation R, ExprArg Val) {
1155 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001156 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001157 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001158}
1159
1160/// The UsualUnaryConversions() function is *not* called by this routine.
1161/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001162bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1163 SourceLocation OpLoc,
1164 const SourceRange &ExprRange,
1165 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001166 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001167 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001168 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001169 if (isSizeof)
1170 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1171 return false;
1172 }
1173
1174 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001175 Diag(OpLoc, diag::ext_sizeof_void_type)
1176 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001177 return false;
1178 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001179
Chris Lattner159fe082009-01-24 19:46:37 +00001180 return DiagnoseIncompleteType(OpLoc, exprType,
1181 isSizeof ? diag::err_sizeof_incomplete_type :
1182 diag::err_alignof_incomplete_type,
1183 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001184}
1185
Chris Lattner8d9f7962009-01-24 20:17:12 +00001186bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1187 const SourceRange &ExprRange) {
1188 E = E->IgnoreParens();
1189
1190 // alignof decl is always ok.
1191 if (isa<DeclRefExpr>(E))
1192 return false;
1193
1194 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1195 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1196 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001197 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001198 return true;
1199 }
1200 // Other fields are ok.
1201 return false;
1202 }
1203 }
1204 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1205}
1206
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001207/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1208/// the same for @c alignof and @c __alignof
1209/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001210Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001211Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1212 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001213 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001214 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001215
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001216 QualType ArgTy;
1217 SourceRange Range;
1218 if (isType) {
1219 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1220 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001221
1222 // Verify that the operand is valid.
1223 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1224 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001225 } else {
1226 // Get the end location.
1227 Expr *ArgEx = (Expr *)TyOrEx;
1228 Range = ArgEx->getSourceRange();
1229 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001230
1231 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001232 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001233 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001234 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001235 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1236 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1237 isInvalid = true;
1238 } else {
1239 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1240 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001241
1242 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001243 DeleteExpr(ArgEx);
1244 return ExprError();
1245 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001246 }
1247
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001248 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001249 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001250 Context.getSizeType(), OpLoc,
1251 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001252}
1253
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001254QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Chris Lattner03931a72007-08-24 21:16:53 +00001255 DefaultFunctionArrayConversion(V);
1256
Chris Lattnera16e42d2007-08-26 05:39:26 +00001257 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001258 if (const ComplexType *CT = V->getType()->getAsComplexType())
1259 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001260
1261 // Otherwise they pass through real integer and floating point types here.
1262 if (V->getType()->isArithmeticType())
1263 return V->getType();
1264
1265 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001266 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1267 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001268 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001269}
1270
1271
Chris Lattner4b009652007-07-25 00:24:17 +00001272
Sebastian Redl8b769972009-01-19 00:08:26 +00001273Action::OwningExprResult
1274Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1275 tok::TokenKind Kind, ExprArg Input) {
1276 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001277
Chris Lattner4b009652007-07-25 00:24:17 +00001278 UnaryOperator::Opcode Opc;
1279 switch (Kind) {
1280 default: assert(0 && "Unknown unary op!");
1281 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1282 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1283 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001284
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001285 if (getLangOptions().CPlusPlus &&
1286 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1287 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001288 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001289 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1290
1291 // C++ [over.inc]p1:
1292 //
1293 // [...] If the function is a member function with one
1294 // parameter (which shall be of type int) or a non-member
1295 // function with two parameters (the second of which shall be
1296 // of type int), it defines the postfix increment operator ++
1297 // for objects of that type. When the postfix increment is
1298 // called as a result of using the ++ operator, the int
1299 // argument will have value zero.
1300 Expr *Args[2] = {
1301 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001302 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1303 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001304 };
1305
1306 // Build the candidate set for overloading
1307 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001308 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1309 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001310
1311 // Perform overload resolution.
1312 OverloadCandidateSet::iterator Best;
1313 switch (BestViableFunction(CandidateSet, Best)) {
1314 case OR_Success: {
1315 // We found a built-in operator or an overloaded operator.
1316 FunctionDecl *FnDecl = Best->Function;
1317
1318 if (FnDecl) {
1319 // We matched an overloaded operator. Build a call to that
1320 // operator.
1321
1322 // Convert the arguments.
1323 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1324 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001325 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001326 } else {
1327 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001328 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001329 FnDecl->getParamDecl(0)->getType(),
1330 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001331 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001332 }
1333
1334 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001335 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001336 = FnDecl->getType()->getAsFunctionType()->getResultType();
1337 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001338
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001339 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001340 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001341 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001342 UsualUnaryConversions(FnExpr);
1343
Sebastian Redl8b769972009-01-19 00:08:26 +00001344 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001345 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1346 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001347 } else {
1348 // We matched a built-in operator. Convert the arguments, then
1349 // break out so that we will build the appropriate built-in
1350 // operator node.
1351 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1352 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001353 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001354
1355 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001356 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001357 }
1358
1359 case OR_No_Viable_Function:
1360 // No viable function; fall through to handling this as a
1361 // built-in operator, which will produce an error message for us.
1362 break;
1363
1364 case OR_Ambiguous:
1365 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1366 << UnaryOperator::getOpcodeStr(Opc)
1367 << Arg->getSourceRange();
1368 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001369 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001370
1371 case OR_Deleted:
1372 Diag(OpLoc, diag::err_ovl_deleted_oper)
1373 << Best->Function->isDeleted()
1374 << UnaryOperator::getOpcodeStr(Opc)
1375 << Arg->getSourceRange();
1376 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1377 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001378 }
1379
1380 // Either we found no viable overloaded operator or we matched a
1381 // built-in operator. In either case, fall through to trying to
1382 // build a built-in operation.
1383 }
1384
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001385 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1386 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001387 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001388 return ExprError();
1389 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001390 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001391}
1392
Sebastian Redl8b769972009-01-19 00:08:26 +00001393Action::OwningExprResult
1394Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1395 ExprArg Idx, SourceLocation RLoc) {
1396 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1397 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001398
Douglas Gregor80723c52008-11-19 17:17:41 +00001399 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001400 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001401 LHSExp->getType()->isEnumeralType() ||
1402 RHSExp->getType()->isRecordType() ||
1403 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001404 // Add the appropriate overloaded operators (C++ [over.match.oper])
1405 // to the candidate set.
1406 OverloadCandidateSet CandidateSet;
1407 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001408 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1409 SourceRange(LLoc, RLoc)))
1410 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001411
Douglas Gregor80723c52008-11-19 17:17:41 +00001412 // Perform overload resolution.
1413 OverloadCandidateSet::iterator Best;
1414 switch (BestViableFunction(CandidateSet, Best)) {
1415 case OR_Success: {
1416 // We found a built-in operator or an overloaded operator.
1417 FunctionDecl *FnDecl = Best->Function;
1418
1419 if (FnDecl) {
1420 // We matched an overloaded operator. Build a call to that
1421 // operator.
1422
1423 // Convert the arguments.
1424 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1425 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1426 PerformCopyInitialization(RHSExp,
1427 FnDecl->getParamDecl(0)->getType(),
1428 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001429 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001430 } else {
1431 // Convert the arguments.
1432 if (PerformCopyInitialization(LHSExp,
1433 FnDecl->getParamDecl(0)->getType(),
1434 "passing") ||
1435 PerformCopyInitialization(RHSExp,
1436 FnDecl->getParamDecl(1)->getType(),
1437 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001438 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001439 }
1440
1441 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001442 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001443 = FnDecl->getType()->getAsFunctionType()->getResultType();
1444 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001445
Douglas Gregor80723c52008-11-19 17:17:41 +00001446 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001447 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1448 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001449 UsualUnaryConversions(FnExpr);
1450
Sebastian Redl8b769972009-01-19 00:08:26 +00001451 Base.release();
1452 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001453 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001454 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001455 } else {
1456 // We matched a built-in operator. Convert the arguments, then
1457 // break out so that we will build the appropriate built-in
1458 // operator node.
1459 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1460 "passing") ||
1461 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1462 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001463 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001464
1465 break;
1466 }
1467 }
1468
1469 case OR_No_Viable_Function:
1470 // No viable function; fall through to handling this as a
1471 // built-in operator, which will produce an error message for us.
1472 break;
1473
1474 case OR_Ambiguous:
1475 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1476 << "[]"
1477 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1478 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001479 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001480
1481 case OR_Deleted:
1482 Diag(LLoc, diag::err_ovl_deleted_oper)
1483 << Best->Function->isDeleted()
1484 << "[]"
1485 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1486 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1487 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001488 }
1489
1490 // Either we found no viable overloaded operator or we matched a
1491 // built-in operator. In either case, fall through to trying to
1492 // build a built-in operation.
1493 }
1494
Chris Lattner4b009652007-07-25 00:24:17 +00001495 // Perform default conversions.
1496 DefaultFunctionArrayConversion(LHSExp);
1497 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001498
Chris Lattner4b009652007-07-25 00:24:17 +00001499 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1500
1501 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001502 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001503 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001504 // and index from the expression types.
1505 Expr *BaseExpr, *IndexExpr;
1506 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001507 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001508 BaseExpr = LHSExp;
1509 IndexExpr = RHSExp;
1510 // FIXME: need to deal with const...
1511 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001512 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001513 // Handle the uncommon case of "123[Ptr]".
1514 BaseExpr = RHSExp;
1515 IndexExpr = LHSExp;
1516 // FIXME: need to deal with const...
1517 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001518 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1519 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001520 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001521
Chris Lattner4b009652007-07-25 00:24:17 +00001522 // FIXME: need to deal with const...
1523 ResultType = VTy->getElementType();
1524 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001525 return ExprError(Diag(LHSExp->getLocStart(),
1526 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1527 }
Chris Lattner4b009652007-07-25 00:24:17 +00001528 // C99 6.5.2.1p1
1529 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001530 return ExprError(Diag(IndexExpr->getLocStart(),
1531 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001532
1533 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1534 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001535 // void (*)(int)) and pointers to incomplete types. Functions are not
1536 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001537 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001538 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001539 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001540 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001541
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 Base.release();
1543 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001544 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001545 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001546}
1547
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001548QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001549CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001550 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001551 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001552
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001553 // The vector accessor can't exceed the number of elements.
1554 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001555
Mike Stump9afab102009-02-19 03:04:26 +00001556 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001557 // special names that indicate a subset of exactly half the elements are
1558 // to be selected.
1559 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001560
Nate Begeman1486b502009-01-18 01:47:54 +00001561 // This flag determines whether or not CompName has an 's' char prefix,
1562 // indicating that it is a string of hex values to be used as vector indices.
1563 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001564
1565 // Check that we've found one of the special components, or that the component
1566 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001567 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001568 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1569 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001570 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001571 do
1572 compStr++;
1573 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001574 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001575 do
1576 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001577 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001578 }
Nate Begeman1486b502009-01-18 01:47:54 +00001579
Mike Stump9afab102009-02-19 03:04:26 +00001580 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001581 // We didn't get to the end of the string. This means the component names
1582 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001583 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1584 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001585 return QualType();
1586 }
Mike Stump9afab102009-02-19 03:04:26 +00001587
Nate Begeman1486b502009-01-18 01:47:54 +00001588 // Ensure no component accessor exceeds the width of the vector type it
1589 // operates on.
1590 if (!HalvingSwizzle) {
1591 compStr = CompName.getName();
1592
1593 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001594 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001595
1596 while (*compStr) {
1597 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1598 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1599 << baseType << SourceRange(CompLoc);
1600 return QualType();
1601 }
1602 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001603 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001604
Nate Begeman1486b502009-01-18 01:47:54 +00001605 // If this is a halving swizzle, verify that the base type has an even
1606 // number of elements.
1607 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001608 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001609 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001610 return QualType();
1611 }
Mike Stump9afab102009-02-19 03:04:26 +00001612
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001613 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001614 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001615 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001616 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001617 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001618 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1619 : CompName.getLength();
1620 if (HexSwizzle)
1621 CompSize--;
1622
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001623 if (CompSize == 1)
1624 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001625
Nate Begemanaf6ed502008-04-18 23:10:10 +00001626 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001627 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001628 // diagostics look bad. We want extended vector types to appear built-in.
1629 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1630 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1631 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001632 }
1633 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001634}
1635
Chris Lattner2cb744b2009-02-15 22:43:40 +00001636
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001637/// constructSetterName - Return the setter name for the given
1638/// identifier, i.e. "set" + Name where the initial character of Name
1639/// has been capitalized.
1640// FIXME: Merge with same routine in Parser. But where should this
1641// live?
1642static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1643 const IdentifierInfo *Name) {
1644 llvm::SmallString<100> SelectorName;
1645 SelectorName = "set";
1646 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1647 SelectorName[3] = toupper(SelectorName[3]);
1648 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1649}
1650
Sebastian Redl8b769972009-01-19 00:08:26 +00001651Action::OwningExprResult
1652Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1653 tok::TokenKind OpKind, SourceLocation MemberLoc,
1654 IdentifierInfo &Member) {
1655 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001656 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001657
1658 // Perform default conversions.
1659 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001660
Steve Naroff2cb66382007-07-26 03:11:44 +00001661 QualType BaseType = BaseExpr->getType();
1662 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001663
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001664 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1665 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001666 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001667 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001668 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001669 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001670 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1671 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001672 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001673 return ExprError(Diag(MemberLoc,
1674 diag::err_typecheck_member_reference_arrow)
1675 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001676 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001677
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001678 // Handle field access to simple records. This also handles access to fields
1679 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001680 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001681 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001682 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001683 diag::err_typecheck_incomplete_tag,
1684 BaseExpr->getSourceRange()))
1685 return ExprError();
1686
Steve Naroff2cb66382007-07-26 03:11:44 +00001687 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001688 // FIXME: Qualified name lookup for C++ is a bit more complicated
1689 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001690 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001691 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001692 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001693
Douglas Gregor09be81b2009-02-04 17:27:36 +00001694 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001695 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001696 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1697 << &Member << BaseExpr->getSourceRange());
1698 else if (Result.isAmbiguous()) {
1699 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1700 MemberLoc, BaseExpr->getSourceRange());
1701 return ExprError();
1702 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001703 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001704
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001705 // If the decl being referenced had an error, return an error for this
1706 // sub-expr without emitting another error, in order to avoid cascading
1707 // error cases.
1708 if (MemberDecl->isInvalidDecl())
1709 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001710
Douglas Gregoraa57e862009-02-18 21:56:37 +00001711 // Check the use of this field
1712 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1713 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001714
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001715 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001716 // We may have found a field within an anonymous union or struct
1717 // (C++ [class.union]).
1718 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001719 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001720 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001721
Douglas Gregor82d44772008-12-20 23:49:58 +00001722 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1723 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001724 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001725 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1726 MemberType = Ref->getPointeeType();
1727 else {
1728 unsigned combinedQualifiers =
1729 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001730 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001731 combinedQualifiers &= ~QualType::Const;
1732 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1733 }
Eli Friedman76b49832008-02-06 22:48:16 +00001734
Steve Naroff774e4152009-01-21 00:14:39 +00001735 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1736 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001737 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001738 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001739 Var, MemberLoc,
1740 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001741 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001742 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001743 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001744 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001745 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001746 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001747 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001748 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001749 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1750 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001751 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001752 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1753 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001754
Douglas Gregor82d44772008-12-20 23:49:58 +00001755 // We found a declaration kind that we didn't expect. This is a
1756 // generic error message that tells the user that she can't refer
1757 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001758 return ExprError(Diag(MemberLoc,
1759 diag::err_typecheck_member_reference_unknown)
1760 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001761 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001762
Chris Lattnere9d71612008-07-21 04:59:05 +00001763 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1764 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001765 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001766 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001767 // If the decl being referenced had an error, return an error for this
1768 // sub-expr without emitting another error, in order to avoid cascading
1769 // error cases.
1770 if (IV->isInvalidDecl())
1771 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001772
1773 // Check whether we can reference this field.
1774 if (DiagnoseUseOfDecl(IV, MemberLoc))
1775 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001776
1777 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001778 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001779 OpKind == tok::arrow);
1780 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001781 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001782 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001783 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1784 << IFTy->getDecl()->getDeclName() << &Member
1785 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001786 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001787
Chris Lattnere9d71612008-07-21 04:59:05 +00001788 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1789 // pointer to a (potentially qualified) interface type.
1790 const PointerType *PTy;
1791 const ObjCInterfaceType *IFTy;
1792 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1793 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1794 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001795
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001796 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001797 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001798 // Check whether we can reference this property.
1799 if (DiagnoseUseOfDecl(PD, MemberLoc))
1800 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001801
Steve Naroff774e4152009-01-21 00:14:39 +00001802 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001803 MemberLoc, BaseExpr));
1804 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001805
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001806 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001807 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1808 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001809 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001810 // Check whether we can reference this property.
1811 if (DiagnoseUseOfDecl(PD, MemberLoc))
1812 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001813
Steve Naroff774e4152009-01-21 00:14:39 +00001814 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001815 MemberLoc, BaseExpr));
1816 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001817
1818 // If that failed, look for an "implicit" property by seeing if the nullary
1819 // selector is implemented.
1820
1821 // FIXME: The logic for looking up nullary and unary selectors should be
1822 // shared with the code in ActOnInstanceMessage.
1823
1824 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1825 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001826
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001827 // If this reference is in an @implementation, check for 'private' methods.
1828 if (!Getter)
1829 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1830 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001831 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001832 ObjCImplementations[ClassDecl->getIdentifier()])
1833 Getter = ImpDecl->getInstanceMethod(Sel);
1834
Steve Naroff04151f32008-10-22 19:16:27 +00001835 // Look through local category implementations associated with the class.
1836 if (!Getter) {
1837 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1838 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1839 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1840 }
1841 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001842 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001843 // Check if we can reference this property.
1844 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1845 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001846
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001847 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001848 // will look for the matching setter, in case it is needed.
1849 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1850 &Member);
1851 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1852 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1853 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001854 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001855 // methods.
1856 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1857 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001858 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001859 ObjCImplementations[ClassDecl->getIdentifier()])
1860 Setter = ImpDecl->getInstanceMethod(SetterSel);
1861 }
1862 // Look through local category implementations associated with the class.
1863 if (!Setter) {
1864 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1865 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1866 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1867 }
1868 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001869
Douglas Gregoraa57e862009-02-18 21:56:37 +00001870 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1871 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001872
Sebastian Redl8b769972009-01-19 00:08:26 +00001873 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001874 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001875 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001876 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001877
1878 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1879 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001880 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001881 // Handle properties on qualified "id" protocols.
1882 const ObjCQualifiedIdType *QIdTy;
1883 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1884 // Check protocols on qualified interfaces.
1885 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001886 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001887 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001888 // Check the use of this declaration
1889 if (DiagnoseUseOfDecl(PD, MemberLoc))
1890 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001891
Steve Naroff774e4152009-01-21 00:14:39 +00001892 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001893 MemberLoc, BaseExpr));
1894 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001895 // Also must look for a getter name which uses property syntax.
1896 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1897 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001898 // Check the use of this method.
1899 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1900 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001901
1902 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001903 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001904 }
1905 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001906
1907 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1908 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001909 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001910 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001911 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001912 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1913 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001914 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001915 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001916 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001917 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001918
1919 return ExprError(Diag(MemberLoc,
1920 diag::err_typecheck_member_reference_struct_union)
1921 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001922}
1923
Douglas Gregor3257fb52008-12-22 05:46:06 +00001924/// ConvertArgumentsForCall - Converts the arguments specified in
1925/// Args/NumArgs to the parameter types of the function FDecl with
1926/// function prototype Proto. Call is the call expression itself, and
1927/// Fn is the function expression. For a C++ member function, this
1928/// routine does not attempt to convert the object argument. Returns
1929/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001930bool
1931Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001932 FunctionDecl *FDecl,
1933 const FunctionTypeProto *Proto,
1934 Expr **Args, unsigned NumArgs,
1935 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001936 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001937 // assignment, to the types of the corresponding parameter, ...
1938 unsigned NumArgsInProto = Proto->getNumArgs();
1939 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001940 bool Invalid = false;
1941
Douglas Gregor3257fb52008-12-22 05:46:06 +00001942 // If too few arguments are available (and we don't have default
1943 // arguments for the remaining parameters), don't make the call.
1944 if (NumArgs < NumArgsInProto) {
1945 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1946 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1947 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1948 // Use default arguments for missing arguments
1949 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001950 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001951 }
1952
1953 // If too many are passed and not variadic, error on the extras and drop
1954 // them.
1955 if (NumArgs > NumArgsInProto) {
1956 if (!Proto->isVariadic()) {
1957 Diag(Args[NumArgsInProto]->getLocStart(),
1958 diag::err_typecheck_call_too_many_args)
1959 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1960 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1961 Args[NumArgs-1]->getLocEnd());
1962 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001963 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001964 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001965 }
1966 NumArgsToCheck = NumArgsInProto;
1967 }
Mike Stump9afab102009-02-19 03:04:26 +00001968
Douglas Gregor3257fb52008-12-22 05:46:06 +00001969 // Continue to check argument types (even if we have too few/many args).
1970 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1971 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001972
Douglas Gregor3257fb52008-12-22 05:46:06 +00001973 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001974 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001975 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001976
1977 // Pass the argument.
1978 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1979 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001980 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001981 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001982 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001983 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00001984
Douglas Gregor3257fb52008-12-22 05:46:06 +00001985 Call->setArg(i, Arg);
1986 }
Mike Stump9afab102009-02-19 03:04:26 +00001987
Douglas Gregor3257fb52008-12-22 05:46:06 +00001988 // If this is a variadic call, handle args passed through "...".
1989 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001990 VariadicCallType CallType = VariadicFunction;
1991 if (Fn->getType()->isBlockPointerType())
1992 CallType = VariadicBlock; // Block
1993 else if (isa<MemberExpr>(Fn))
1994 CallType = VariadicMethod;
1995
Douglas Gregor3257fb52008-12-22 05:46:06 +00001996 // Promote the arguments (C99 6.5.2.2p7).
1997 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1998 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001999 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002000 Call->setArg(i, Arg);
2001 }
2002 }
2003
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002004 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002005}
2006
Steve Naroff87d58b42007-09-16 03:34:24 +00002007/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002008/// This provides the location of the left/right parens and a list of comma
2009/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002010Action::OwningExprResult
2011Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2012 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002013 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002014 unsigned NumArgs = args.size();
2015 Expr *Fn = static_cast<Expr *>(fn.release());
2016 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002017 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002018 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002019 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002020
Douglas Gregor3257fb52008-12-22 05:46:06 +00002021 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002022 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002023 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002024 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2025 bool Dependent = false;
2026 if (Fn->isTypeDependent())
2027 Dependent = true;
2028 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2029 Dependent = true;
2030
2031 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002032 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002033 Context.DependentTy, RParenLoc));
2034
2035 // Determine whether this is a call to an object (C++ [over.call.object]).
2036 if (Fn->getType()->isRecordType())
2037 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2038 CommaLocs, RParenLoc));
2039
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002040 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002041 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2042 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2043 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002044 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2045 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002046 }
2047
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002048 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002049 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002050 Expr *FnExpr = Fn;
2051 bool ADL = true;
2052 while (true) {
2053 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2054 FnExpr = IcExpr->getSubExpr();
2055 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002056 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002057 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002058 ADL = false;
2059 FnExpr = PExpr->getSubExpr();
2060 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002061 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002062 == UnaryOperator::AddrOf) {
2063 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002064 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2065 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2066 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2067 break;
Mike Stump9afab102009-02-19 03:04:26 +00002068 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002069 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2070 UnqualifiedName = DepName->getName();
2071 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002072 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002073 // Any kind of name that does not refer to a declaration (or
2074 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2075 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002076 break;
2077 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002078 }
Mike Stump9afab102009-02-19 03:04:26 +00002079
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002080 OverloadedFunctionDecl *Ovl = 0;
2081 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002082 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002083 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2084 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002085
Douglas Gregorfcb19192009-02-11 23:02:49 +00002086 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002087 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002088 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002089 ADL = false;
2090
Douglas Gregorfcb19192009-02-11 23:02:49 +00002091 // We don't perform ADL in C.
2092 if (!getLangOptions().CPlusPlus)
2093 ADL = false;
2094
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002095 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002096 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2097 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002098 NumArgs, CommaLocs, RParenLoc, ADL);
2099 if (!FDecl)
2100 return ExprError();
2101
2102 // Update Fn to refer to the actual function selected.
2103 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002104 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002105 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002106 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2107 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002108 false, false,
2109 QDRExpr->getSourceRange().getBegin());
2110 else
Mike Stump9afab102009-02-19 03:04:26 +00002111 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002112 Fn->getSourceRange().getBegin());
2113 Fn->Destroy(Context);
2114 Fn = NewFn;
2115 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002116 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002117
2118 // Promote the function operand.
2119 UsualUnaryConversions(Fn);
2120
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002121 // Make the call expr early, before semantic checks. This guarantees cleanup
2122 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002123 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2124 Args, NumArgs,
2125 Context.BoolTy,
2126 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002127
Steve Naroffd6163f32008-09-05 22:11:13 +00002128 const FunctionType *FuncT;
2129 if (!Fn->getType()->isBlockPointerType()) {
2130 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2131 // have type pointer to function".
2132 const PointerType *PT = Fn->getType()->getAsPointerType();
2133 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002134 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2135 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002136 FuncT = PT->getPointeeType()->getAsFunctionType();
2137 } else { // This is a block call.
2138 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2139 getAsFunctionType();
2140 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002141 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002142 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2143 << Fn->getType() << Fn->getSourceRange());
2144
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002145 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002146 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002147
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002148 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002149 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002150 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002151 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002152 } else {
2153 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002154
Steve Naroffdb65e052007-08-28 23:30:39 +00002155 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002156 for (unsigned i = 0; i != NumArgs; i++) {
2157 Expr *Arg = Args[i];
2158 DefaultArgumentPromotion(Arg);
2159 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002160 }
Chris Lattner4b009652007-07-25 00:24:17 +00002161 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002162
Douglas Gregor3257fb52008-12-22 05:46:06 +00002163 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2164 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002165 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2166 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002167
Chris Lattner2e64c072007-08-10 20:18:51 +00002168 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002169 if (FDecl)
2170 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002171
Sebastian Redl8b769972009-01-19 00:08:26 +00002172 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002173}
2174
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002175Action::OwningExprResult
2176Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2177 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002178 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002179 QualType literalType = QualType::getFromOpaquePtr(Ty);
2180 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002181 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002182 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002183
Eli Friedman8c2173d2008-05-20 05:22:08 +00002184 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002185 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002186 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2187 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002188 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2189 diag::err_typecheck_decl_incomplete_type,
2190 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002191 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002192
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002193 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002194 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002195 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002196
Chris Lattnere5cb5862008-12-04 23:50:19 +00002197 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002198 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002199 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002200 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002201 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002202 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002203 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002204 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002205}
2206
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002207Action::OwningExprResult
2208Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2209 InitListDesignations &Designators,
2210 SourceLocation RBraceLoc) {
2211 unsigned NumInit = initlist.size();
2212 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002213
Steve Naroff0acc9c92007-09-15 18:49:24 +00002214 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002215 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002216
Mike Stump9afab102009-02-19 03:04:26 +00002217 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002218 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002219 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002220 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002221}
2222
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002223/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002224bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002225 UsualUnaryConversions(castExpr);
2226
2227 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2228 // type needs to be scalar.
2229 if (castType->isVoidType()) {
2230 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002231 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2232 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002233 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002234 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2235 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2236 (castType->isStructureType() || castType->isUnionType())) {
2237 // GCC struct/union extension: allow cast to self.
2238 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2239 << castType << castExpr->getSourceRange();
2240 } else if (castType->isUnionType()) {
2241 // GCC cast to union extension
2242 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2243 RecordDecl::field_iterator Field, FieldEnd;
2244 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2245 Field != FieldEnd; ++Field) {
2246 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2247 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2248 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2249 << castExpr->getSourceRange();
2250 break;
2251 }
2252 }
2253 if (Field == FieldEnd)
2254 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2255 << castExpr->getType() << castExpr->getSourceRange();
2256 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002257 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002258 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002259 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002260 }
Mike Stump9afab102009-02-19 03:04:26 +00002261 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002262 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002263 return Diag(castExpr->getLocStart(),
2264 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002265 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002266 } else if (castExpr->getType()->isVectorType()) {
2267 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2268 return true;
2269 } else if (castType->isVectorType()) {
2270 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2271 return true;
2272 }
2273 return false;
2274}
2275
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002276bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002277 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002278
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002279 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002280 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002281 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002282 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002283 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002284 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002285 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002286 } else
2287 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002288 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002289 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002290
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002291 return false;
2292}
2293
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002294Action::OwningExprResult
2295Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2296 SourceLocation RParenLoc, ExprArg Op) {
2297 assert((Ty != 0) && (Op.get() != 0) &&
2298 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002299
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002300 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002301 QualType castType = QualType::getFromOpaquePtr(Ty);
2302
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002303 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002304 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002305 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002306 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002307}
2308
Chris Lattner98a425c2007-11-26 01:40:58 +00002309/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2310/// In that case, lex = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002311/// C99 6.5.15
2312QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2313 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002314 UsualUnaryConversions(Cond);
2315 UsualUnaryConversions(LHS);
2316 UsualUnaryConversions(RHS);
2317 QualType CondTy = Cond->getType();
2318 QualType LHSTy = LHS->getType();
2319 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002320
2321 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002322 if (!Cond->isTypeDependent()) {
2323 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2324 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2325 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002326 return QualType();
2327 }
Chris Lattner4b009652007-07-25 00:24:17 +00002328 }
Mike Stump9afab102009-02-19 03:04:26 +00002329
Chris Lattner992ae932008-01-06 22:42:25 +00002330 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002331 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002332 return Context.DependentTy;
2333
Chris Lattner992ae932008-01-06 22:42:25 +00002334 // If both operands have arithmetic type, do the usual arithmetic conversions
2335 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002336 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2337 UsualArithmeticConversions(LHS, RHS);
2338 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002339 }
Mike Stump9afab102009-02-19 03:04:26 +00002340
Chris Lattner992ae932008-01-06 22:42:25 +00002341 // If both operands are the same structure or union type, the result is that
2342 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002343 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2344 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002345 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002346 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002347 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002348 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002349 }
Mike Stump9afab102009-02-19 03:04:26 +00002350
Chris Lattner992ae932008-01-06 22:42:25 +00002351 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002352 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002353 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2354 if (!LHSTy->isVoidType())
2355 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2356 << RHS->getSourceRange();
2357 if (!RHSTy->isVoidType())
2358 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2359 << LHS->getSourceRange();
2360 ImpCastExprToType(LHS, Context.VoidTy);
2361 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002362 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002363 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002364 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2365 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002366 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2367 Context.isObjCObjectPointerType(LHSTy)) &&
2368 RHS->isNullPointerConstant(Context)) {
2369 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2370 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002371 }
Chris Lattnere2897262009-02-18 04:28:32 +00002372 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2373 Context.isObjCObjectPointerType(RHSTy)) &&
2374 LHS->isNullPointerConstant(Context)) {
2375 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2376 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002377 }
Mike Stump9afab102009-02-19 03:04:26 +00002378
Chris Lattner0ac51632008-01-06 22:50:31 +00002379 // Handle the case where both operands are pointers before we handle null
2380 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002381 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2382 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002383 // get the "pointed to" types
2384 QualType lhptee = LHSPT->getPointeeType();
2385 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002386
Chris Lattner71225142007-07-31 21:27:01 +00002387 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2388 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002389 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002390 // Figure out necessary qualifiers (C99 6.5.15p6)
2391 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002392 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002393 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2394 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002395 return destType;
2396 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002397 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002398 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002399 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002400 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2401 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002402 return destType;
2403 }
Chris Lattner4b009652007-07-25 00:24:17 +00002404
Chris Lattner9c039b52009-02-18 04:38:20 +00002405 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002406 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002407 return LHSTy;
2408 }
Mike Stump9afab102009-02-19 03:04:26 +00002409
Chris Lattnere2897262009-02-18 04:28:32 +00002410 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002411
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002412 // If either type is an Objective-C object type then check
2413 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002414 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002415 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002416 // If both operands are interfaces and either operand can be
2417 // assigned to the other, use that type as the composite
2418 // type. This allows
2419 // xxx ? (A*) a : (B*) b
2420 // where B is a subclass of A.
2421 //
2422 // Additionally, as for assignment, if either type is 'id'
2423 // allow silent coercion. Finally, if the types are
2424 // incompatible then make sure to use 'id' as the composite
2425 // type so the result is acceptable for sending messages to.
2426
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002427 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002428 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002429 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2430 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2431 if (LHSIface && RHSIface &&
2432 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002433 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002434 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002435 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002436 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002437 } else if (Context.isObjCIdStructType(lhptee) ||
2438 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002439 compositeType = Context.getObjCIdType();
2440 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002441 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002442 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002443 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002444 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002445 ImpCastExprToType(LHS, incompatTy);
2446 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002447 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002448 }
Mike Stump9afab102009-02-19 03:04:26 +00002449 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002450 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002451 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2452 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002453 // In this situation, we assume void* type. No especially good
2454 // reason, but this is what gcc does, and we do have to pick
2455 // to get a consistent AST.
2456 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002457 ImpCastExprToType(LHS, incompatTy);
2458 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002459 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002460 }
2461 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002462 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2463 // differently qualified versions of compatible types, the result type is
2464 // a pointer to an appropriately qualified version of the *composite*
2465 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002466 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002467 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002468 ImpCastExprToType(LHS, compositeType);
2469 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002470 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002471 }
Chris Lattner4b009652007-07-25 00:24:17 +00002472 }
Mike Stump9afab102009-02-19 03:04:26 +00002473
Chris Lattner9c039b52009-02-18 04:38:20 +00002474 // Selection between block pointer types is ok as long as they are the same.
2475 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2476 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2477 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002478
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002479 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2480 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002481 // id with statically typed objects).
2482 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002483 // GCC allows qualified id and any Objective-C type to devolve to
2484 // id. Currently localizing to here until clear this should be
2485 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002486 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002487 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002488 Context.isObjCObjectPointerType(RHSTy)) ||
2489 (RHSTy->isObjCQualifiedIdType() &&
2490 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002491 // FIXME: This is not the correct composite type. This only
2492 // happens to work because id can more or less be used anywhere,
2493 // however this may change the type of method sends.
2494 // FIXME: gcc adds some type-checking of the arguments and emits
2495 // (confusing) incompatible comparison warnings in some
2496 // cases. Investigate.
2497 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002498 ImpCastExprToType(LHS, compositeType);
2499 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002500 return compositeType;
2501 }
2502 }
2503
Chris Lattner992ae932008-01-06 22:42:25 +00002504 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002505 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2506 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002507 return QualType();
2508}
2509
Steve Naroff87d58b42007-09-16 03:34:24 +00002510/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002511/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002512Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2513 SourceLocation ColonLoc,
2514 ExprArg Cond, ExprArg LHS,
2515 ExprArg RHS) {
2516 Expr *CondExpr = (Expr *) Cond.get();
2517 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002518
2519 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2520 // was the condition.
2521 bool isLHSNull = LHSExpr == 0;
2522 if (isLHSNull)
2523 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002524
2525 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002526 RHSExpr, QuestionLoc);
2527 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002528 return ExprError();
2529
2530 Cond.release();
2531 LHS.release();
2532 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002533 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002534 isLHSNull ? 0 : LHSExpr,
2535 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002536}
2537
Chris Lattner4b009652007-07-25 00:24:17 +00002538
2539// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002540// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002541// routine is it effectively iqnores the qualifiers on the top level pointee.
2542// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2543// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002544Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002545Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2546 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002547
Chris Lattner4b009652007-07-25 00:24:17 +00002548 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002549 lhptee = lhsType->getAsPointerType()->getPointeeType();
2550 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002551
Chris Lattner4b009652007-07-25 00:24:17 +00002552 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002553 lhptee = Context.getCanonicalType(lhptee);
2554 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002555
Chris Lattner005ed752008-01-04 18:04:52 +00002556 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002557
2558 // C99 6.5.16.1p1: This following citation is common to constraints
2559 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2560 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002561 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002562 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002563 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002564
Mike Stump9afab102009-02-19 03:04:26 +00002565 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2566 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002567 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002568 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002569 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002570 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002571
Chris Lattner4ca3d772008-01-03 22:56:36 +00002572 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002573 assert(rhptee->isFunctionType());
2574 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002575 }
Mike Stump9afab102009-02-19 03:04:26 +00002576
Chris Lattner4ca3d772008-01-03 22:56:36 +00002577 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002578 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002579 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002580
2581 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002582 assert(lhptee->isFunctionType());
2583 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002584 }
Mike Stump9afab102009-02-19 03:04:26 +00002585 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002586 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002587 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002588 rhptee.getUnqualifiedType()))
2589 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002590 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002591}
2592
Steve Naroff3454b6c2008-09-04 15:10:53 +00002593/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2594/// block pointer types are compatible or whether a block and normal pointer
2595/// are compatible. It is more restrict than comparing two function pointer
2596// types.
Mike Stump9afab102009-02-19 03:04:26 +00002597Sema::AssignConvertType
2598Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002599 QualType rhsType) {
2600 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002601
Steve Naroff3454b6c2008-09-04 15:10:53 +00002602 // get the "pointed to" type (ignoring qualifiers at the top level)
2603 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002604 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2605
Steve Naroff3454b6c2008-09-04 15:10:53 +00002606 // make sure we operate on the canonical type
2607 lhptee = Context.getCanonicalType(lhptee);
2608 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002609
Steve Naroff3454b6c2008-09-04 15:10:53 +00002610 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002611
Steve Naroff3454b6c2008-09-04 15:10:53 +00002612 // For blocks we enforce that qualifiers are identical.
2613 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2614 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002615
Steve Naroff3454b6c2008-09-04 15:10:53 +00002616 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002617 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002618 return ConvTy;
2619}
2620
Mike Stump9afab102009-02-19 03:04:26 +00002621/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2622/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002623/// pointers. Here are some objectionable examples that GCC considers warnings:
2624///
2625/// int a, *pint;
2626/// short *pshort;
2627/// struct foo *pfoo;
2628///
2629/// pint = pshort; // warning: assignment from incompatible pointer type
2630/// a = pint; // warning: assignment makes integer from pointer without a cast
2631/// pint = a; // warning: assignment makes pointer from integer without a cast
2632/// pint = pfoo; // warning: assignment from incompatible pointer type
2633///
2634/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002635/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002636///
Chris Lattner005ed752008-01-04 18:04:52 +00002637Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002638Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002639 // Get canonical types. We're not formatting these types, just comparing
2640 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002641 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2642 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002643
2644 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002645 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002646
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002647 // If the left-hand side is a reference type, then we are in a
2648 // (rare!) case where we've allowed the use of references in C,
2649 // e.g., as a parameter type in a built-in function. In this case,
2650 // just make sure that the type referenced is compatible with the
2651 // right-hand side type. The caller is responsible for adjusting
2652 // lhsType so that the resulting expression does not have reference
2653 // type.
2654 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2655 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002656 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002657 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002658 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002659
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002660 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2661 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002662 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002663 // Relax integer conversions like we do for pointers below.
2664 if (rhsType->isIntegerType())
2665 return IntToPointer;
2666 if (lhsType->isIntegerType())
2667 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002668 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002669 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002670
Nate Begemanc5f0f652008-07-14 18:02:46 +00002671 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002672 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002673 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2674 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002675 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002676
Nate Begemanc5f0f652008-07-14 18:02:46 +00002677 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002678 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002679 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002680 if (getLangOptions().LaxVectorConversions &&
2681 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002682 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002683 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002684 }
2685 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002686 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002687
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002688 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002689 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002690
Chris Lattner390564e2008-04-07 06:49:41 +00002691 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002692 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002693 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002694
Chris Lattner390564e2008-04-07 06:49:41 +00002695 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002696 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002697
Steve Naroffa982c712008-09-29 18:10:17 +00002698 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002699 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002700 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002701
2702 // Treat block pointers as objects.
2703 if (getLangOptions().ObjC1 &&
2704 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2705 return Compatible;
2706 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002707 return Incompatible;
2708 }
2709
2710 if (isa<BlockPointerType>(lhsType)) {
2711 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002712 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002713
Steve Naroffa982c712008-09-29 18:10:17 +00002714 // Treat block pointers as objects.
2715 if (getLangOptions().ObjC1 &&
2716 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2717 return Compatible;
2718
Steve Naroff3454b6c2008-09-04 15:10:53 +00002719 if (rhsType->isBlockPointerType())
2720 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002721
Steve Naroff3454b6c2008-09-04 15:10:53 +00002722 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2723 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002724 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002725 }
Chris Lattner1853da22008-01-04 23:18:45 +00002726 return Incompatible;
2727 }
2728
Chris Lattner390564e2008-04-07 06:49:41 +00002729 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002730 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002731 if (lhsType == Context.BoolTy)
2732 return Compatible;
2733
2734 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002735 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002736
Mike Stump9afab102009-02-19 03:04:26 +00002737 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002738 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002739
2740 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002741 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002742 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002743 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002744 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002745
Chris Lattner1853da22008-01-04 23:18:45 +00002746 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002747 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002748 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002749 }
2750 return Incompatible;
2751}
2752
Chris Lattner005ed752008-01-04 18:04:52 +00002753Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002754Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002755 if (getLangOptions().CPlusPlus) {
2756 if (!lhsType->isRecordType()) {
2757 // C++ 5.17p3: If the left operand is not of class type, the
2758 // expression is implicitly converted (C++ 4) to the
2759 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002760 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2761 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002762 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002763 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002764 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002765 }
2766
2767 // FIXME: Currently, we fall through and treat C++ classes like C
2768 // structures.
2769 }
2770
Steve Naroffcdee22d2007-11-27 17:58:44 +00002771 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2772 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002773 if ((lhsType->isPointerType() ||
2774 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002775 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002776 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002777 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002778 return Compatible;
2779 }
Mike Stump9afab102009-02-19 03:04:26 +00002780
Chris Lattner5f505bf2007-10-16 02:55:40 +00002781 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002782 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002783 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002784 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002785 //
Mike Stump9afab102009-02-19 03:04:26 +00002786 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002787 if (!lhsType->isReferenceType())
2788 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002789
Chris Lattner005ed752008-01-04 18:04:52 +00002790 Sema::AssignConvertType result =
2791 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002792
Steve Naroff0f32f432007-08-24 22:33:52 +00002793 // C99 6.5.16.1p2: The value of the right operand is converted to the
2794 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002795 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2796 // so that we can use references in built-in functions even in C.
2797 // The getNonReferenceType() call makes sure that the resulting expression
2798 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002799 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002800 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002801 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002802}
2803
Chris Lattner005ed752008-01-04 18:04:52 +00002804Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002805Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2806 return CheckAssignmentConstraints(lhsType, rhsType);
2807}
2808
Chris Lattner1eafdea2008-11-18 01:30:42 +00002809QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002810 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002811 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002812 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002813 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002814}
2815
Mike Stump9afab102009-02-19 03:04:26 +00002816inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002817 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002818 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002819 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002820 QualType lhsType =
2821 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2822 QualType rhsType =
2823 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002824
Nate Begemanc5f0f652008-07-14 18:02:46 +00002825 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002826 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002827 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002828
Nate Begemanc5f0f652008-07-14 18:02:46 +00002829 // Handle the case of a vector & extvector type of the same size and element
2830 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002831 if (getLangOptions().LaxVectorConversions) {
2832 // FIXME: Should we warn here?
2833 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002834 if (const VectorType *RV = rhsType->getAsVectorType())
2835 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002836 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002837 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002838 }
2839 }
2840 }
Mike Stump9afab102009-02-19 03:04:26 +00002841
Nate Begemanc5f0f652008-07-14 18:02:46 +00002842 // If the lhs is an extended vector and the rhs is a scalar of the same type
2843 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002844 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002845 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002846
2847 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002848 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2849 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002850 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002851 return lhsType;
2852 }
2853 }
2854
Nate Begemanc5f0f652008-07-14 18:02:46 +00002855 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002856 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002857 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002858 QualType eltType = V->getElementType();
2859
Mike Stump9afab102009-02-19 03:04:26 +00002860 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002861 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2862 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002863 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002864 return rhsType;
2865 }
2866 }
2867
Chris Lattner4b009652007-07-25 00:24:17 +00002868 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002869 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002870 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002871 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002872 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002873}
2874
Chris Lattner4b009652007-07-25 00:24:17 +00002875inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002876 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002877{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002878 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002879 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002880
Steve Naroff8f708362007-08-24 19:07:16 +00002881 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002882
Chris Lattner4b009652007-07-25 00:24:17 +00002883 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002884 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002885 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002886}
2887
2888inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002889 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002890{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002891 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2892 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2893 return CheckVectorOperands(Loc, lex, rex);
2894 return InvalidOperands(Loc, lex, rex);
2895 }
Chris Lattner4b009652007-07-25 00:24:17 +00002896
Steve Naroff8f708362007-08-24 19:07:16 +00002897 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002898
Chris Lattner4b009652007-07-25 00:24:17 +00002899 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002900 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002901 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002902}
2903
2904inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002905 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002906{
2907 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002908 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002909
Steve Naroff8f708362007-08-24 19:07:16 +00002910 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002911
Chris Lattner4b009652007-07-25 00:24:17 +00002912 // handle the common case first (both operands are arithmetic).
2913 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002914 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002915
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002916 // Put any potential pointer into PExp
2917 Expr* PExp = lex, *IExp = rex;
2918 if (IExp->getType()->isPointerType())
2919 std::swap(PExp, IExp);
2920
2921 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2922 if (IExp->getType()->isIntegerType()) {
2923 // Check for arithmetic on pointers to incomplete types
2924 if (!PTy->getPointeeType()->isObjectType()) {
2925 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002926 if (getLangOptions().CPlusPlus) {
2927 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2928 << lex->getSourceRange() << rex->getSourceRange();
2929 return QualType();
2930 }
2931
2932 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002933 Diag(Loc, diag::ext_gnu_void_ptr)
2934 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002935 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002936 if (getLangOptions().CPlusPlus) {
2937 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2938 << lex->getType() << lex->getSourceRange();
2939 return QualType();
2940 }
2941
2942 // GNU extension: arithmetic on pointer to function
2943 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002944 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002945 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002946 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002947 diag::err_typecheck_arithmetic_incomplete_type,
2948 lex->getSourceRange(), SourceRange(),
2949 lex->getType());
2950 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002951 }
2952 }
2953 return PExp->getType();
2954 }
2955 }
2956
Chris Lattner1eafdea2008-11-18 01:30:42 +00002957 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002958}
2959
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002960// C99 6.5.6
2961QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002962 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002963 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002964 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002965
Steve Naroff8f708362007-08-24 19:07:16 +00002966 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002967
Chris Lattnerf6da2912007-12-09 21:53:25 +00002968 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002969
Chris Lattnerf6da2912007-12-09 21:53:25 +00002970 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002971 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002972 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002973
Chris Lattnerf6da2912007-12-09 21:53:25 +00002974 // Either ptr - int or ptr - ptr.
2975 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002976 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002977
Chris Lattnerf6da2912007-12-09 21:53:25 +00002978 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002979 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002980 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002981 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002982 Diag(Loc, diag::ext_gnu_void_ptr)
2983 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002984 } else if (lpointee->isFunctionType()) {
2985 if (getLangOptions().CPlusPlus) {
2986 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2987 << lex->getType() << lex->getSourceRange();
2988 return QualType();
2989 }
2990
2991 // GNU extension: arithmetic on pointer to function
2992 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2993 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002994 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002995 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002996 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002997 return QualType();
2998 }
2999 }
3000
3001 // The result type of a pointer-int computation is the pointer type.
3002 if (rex->getType()->isIntegerType())
3003 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003004
Chris Lattnerf6da2912007-12-09 21:53:25 +00003005 // Handle pointer-pointer subtractions.
3006 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003007 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003008
Chris Lattnerf6da2912007-12-09 21:53:25 +00003009 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003010 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003011 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003012 if (rpointee->isVoidType()) {
3013 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003014 Diag(Loc, diag::ext_gnu_void_ptr)
3015 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003016 } else if (rpointee->isFunctionType()) {
3017 if (getLangOptions().CPlusPlus) {
3018 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3019 << rex->getType() << rex->getSourceRange();
3020 return QualType();
3021 }
Mike Stump9afab102009-02-19 03:04:26 +00003022
Douglas Gregorf93eda12009-01-23 19:03:35 +00003023 // GNU extension: arithmetic on pointer to function
3024 if (!lpointee->isFunctionType())
3025 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3026 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003027 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003028 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003029 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003030 return QualType();
3031 }
3032 }
Mike Stump9afab102009-02-19 03:04:26 +00003033
Chris Lattnerf6da2912007-12-09 21:53:25 +00003034 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003035 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003036 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003037 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003038 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003039 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003040 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003041 return QualType();
3042 }
Mike Stump9afab102009-02-19 03:04:26 +00003043
Chris Lattnerf6da2912007-12-09 21:53:25 +00003044 return Context.getPointerDiffType();
3045 }
3046 }
Mike Stump9afab102009-02-19 03:04:26 +00003047
Chris Lattner1eafdea2008-11-18 01:30:42 +00003048 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003049}
3050
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003051// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003052QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003053 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003054 // C99 6.5.7p2: Each of the operands shall have integer type.
3055 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003056 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003057
Chris Lattner2c8bff72007-12-12 05:47:28 +00003058 // Shifts don't perform usual arithmetic conversions, they just do integer
3059 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003060 if (!isCompAssign)
3061 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003062 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003063
Chris Lattner2c8bff72007-12-12 05:47:28 +00003064 // "The type of the result is that of the promoted left operand."
3065 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003066}
3067
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003068// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003069QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003070 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003071 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003072 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003073
Chris Lattner254f3bc2007-08-26 01:18:55 +00003074 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003075 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3076 UsualArithmeticConversions(lex, rex);
3077 else {
3078 UsualUnaryConversions(lex);
3079 UsualUnaryConversions(rex);
3080 }
Chris Lattner4b009652007-07-25 00:24:17 +00003081 QualType lType = lex->getType();
3082 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003083
Ted Kremenek486509e2007-10-29 17:13:39 +00003084 // For non-floating point types, check for self-comparisons of the form
3085 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3086 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003087 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003088 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3089 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003090 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003091 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003092 }
Mike Stump9afab102009-02-19 03:04:26 +00003093
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003094 // The result of comparisons is 'bool' in C++, 'int' in C.
3095 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3096
Chris Lattner254f3bc2007-08-26 01:18:55 +00003097 if (isRelational) {
3098 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003099 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003100 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003101 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003102 if (lType->isFloatingType()) {
3103 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003104 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003105 }
Mike Stump9afab102009-02-19 03:04:26 +00003106
Chris Lattner254f3bc2007-08-26 01:18:55 +00003107 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003108 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003109 }
Mike Stump9afab102009-02-19 03:04:26 +00003110
Chris Lattner22be8422007-08-26 01:10:14 +00003111 bool LHSIsNull = lex->isNullPointerConstant(Context);
3112 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003113
Chris Lattner254f3bc2007-08-26 01:18:55 +00003114 // All of the following pointer related warnings are GCC extensions, except
3115 // when handling null pointer constants. One day, we can consider making them
3116 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003117 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003118 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003119 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003120 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003121 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003122
Steve Naroff3b435622007-11-13 14:57:38 +00003123 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003124 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3125 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003126 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003127 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003128 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003129 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003130 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003131 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003132 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003133 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003134 // Handle block pointer types.
3135 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3136 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3137 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003138
Steve Naroff3454b6c2008-09-04 15:10:53 +00003139 if (!LHSIsNull && !RHSIsNull &&
3140 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003141 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003142 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003143 }
3144 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003145 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003146 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003147 // Allow block pointers to be compared with null pointer constants.
3148 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3149 (lType->isPointerType() && rType->isBlockPointerType())) {
3150 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003151 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003152 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003153 }
3154 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003155 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003156 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003157
Steve Naroff936c4362008-06-03 14:04:54 +00003158 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003159 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003160 const PointerType *LPT = lType->getAsPointerType();
3161 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003162 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003163 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003164 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003165 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003166
Steve Naroff030fcda2008-11-17 19:49:16 +00003167 if (!LPtrToVoid && !RPtrToVoid &&
3168 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003169 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003170 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003171 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003172 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003173 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003174 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003175 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003176 }
Steve Naroff936c4362008-06-03 14:04:54 +00003177 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3178 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003179 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003180 } else {
3181 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003182 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003183 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003184 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003185 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003186 }
Steve Naroff936c4362008-06-03 14:04:54 +00003187 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003188 }
Mike Stump9afab102009-02-19 03:04:26 +00003189 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003190 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003191 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003192 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003193 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003194 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003195 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003196 }
Mike Stump9afab102009-02-19 03:04:26 +00003197 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003198 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003199 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003200 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003201 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003202 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003203 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003204 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003205 // Handle block pointers.
3206 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3207 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003208 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003209 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003210 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003211 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003212 }
3213 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3214 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003215 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003216 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003217 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003218 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003219 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003220 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003221}
3222
Nate Begemanc5f0f652008-07-14 18:02:46 +00003223/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003224/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003225/// like a scalar comparison, a vector comparison produces a vector of integer
3226/// types.
3227QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003228 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003229 bool isRelational) {
3230 // Check to make sure we're operating on vectors of the same type and width,
3231 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003232 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003233 if (vType.isNull())
3234 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003235
Nate Begemanc5f0f652008-07-14 18:02:46 +00003236 QualType lType = lex->getType();
3237 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003238
Nate Begemanc5f0f652008-07-14 18:02:46 +00003239 // For non-floating point types, check for self-comparisons of the form
3240 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3241 // often indicate logic errors in the program.
3242 if (!lType->isFloatingType()) {
3243 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3244 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3245 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003246 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003247 }
Mike Stump9afab102009-02-19 03:04:26 +00003248
Nate Begemanc5f0f652008-07-14 18:02:46 +00003249 // Check for comparisons of floating point operands using != and ==.
3250 if (!isRelational && lType->isFloatingType()) {
3251 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003252 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003253 }
Mike Stump9afab102009-02-19 03:04:26 +00003254
Nate Begemanc5f0f652008-07-14 18:02:46 +00003255 // Return the type for the comparison, which is the same as vector type for
3256 // integer vectors, or an integer type of identical size and number of
3257 // elements for floating point vectors.
3258 if (lType->isIntegerType())
3259 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003260
Nate Begemanc5f0f652008-07-14 18:02:46 +00003261 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003262 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003263 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003264 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003265 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3266 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3267
Mike Stump9afab102009-02-19 03:04:26 +00003268 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003269 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003270 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3271}
3272
Chris Lattner4b009652007-07-25 00:24:17 +00003273inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003274 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003275{
3276 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003277 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003278
Steve Naroff8f708362007-08-24 19:07:16 +00003279 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003280
Chris Lattner4b009652007-07-25 00:24:17 +00003281 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003282 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003283 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003284}
3285
3286inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003287 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003288{
3289 UsualUnaryConversions(lex);
3290 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003291
Eli Friedmanbea3f842008-05-13 20:16:47 +00003292 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003293 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003294 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003295}
3296
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003297/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3298/// is a read-only property; return true if so. A readonly property expression
3299/// depends on various declarations and thus must be treated specially.
3300///
Mike Stump9afab102009-02-19 03:04:26 +00003301static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003302{
3303 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3304 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3305 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3306 QualType BaseType = PropExpr->getBase()->getType();
3307 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003308 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003309 PTy->getPointeeType()->getAsObjCInterfaceType())
3310 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3311 if (S.isPropertyReadonly(PDecl, IFace))
3312 return true;
3313 }
3314 }
3315 return false;
3316}
3317
Chris Lattner4c2642c2008-11-18 01:22:49 +00003318/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3319/// emit an error and return true. If so, return false.
3320static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003321 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3322 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3323 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003324 if (IsLV == Expr::MLV_Valid)
3325 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003326
Chris Lattner4c2642c2008-11-18 01:22:49 +00003327 unsigned Diag = 0;
3328 bool NeedType = false;
3329 switch (IsLV) { // C99 6.5.16p2
3330 default: assert(0 && "Unknown result from isModifiableLvalue!");
3331 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003332 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003333 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3334 NeedType = true;
3335 break;
Mike Stump9afab102009-02-19 03:04:26 +00003336 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003337 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3338 NeedType = true;
3339 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003340 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003341 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3342 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003343 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003344 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3345 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003346 case Expr::MLV_IncompleteType:
3347 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003348 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003349 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3350 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003351 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003352 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3353 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003354 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003355 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3356 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003357 case Expr::MLV_ReadonlyProperty:
3358 Diag = diag::error_readonly_property_assignment;
3359 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003360 case Expr::MLV_NoSetterProperty:
3361 Diag = diag::error_nosetter_property_assignment;
3362 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003363 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003364
Chris Lattner4c2642c2008-11-18 01:22:49 +00003365 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003366 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003367 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003368 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003369 return true;
3370}
3371
3372
3373
3374// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003375QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3376 SourceLocation Loc,
3377 QualType CompoundType) {
3378 // Verify that LHS is a modifiable lvalue, and emit error if not.
3379 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003380 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003381
3382 QualType LHSType = LHS->getType();
3383 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003384
Chris Lattner005ed752008-01-04 18:04:52 +00003385 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003386 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003387 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003388 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003389 // Special case of NSObject attributes on c-style pointer types.
3390 if (ConvTy == IncompatiblePointer &&
3391 ((Context.isObjCNSObjectType(LHSType) &&
3392 Context.isObjCObjectPointerType(RHSType)) ||
3393 (Context.isObjCNSObjectType(RHSType) &&
3394 Context.isObjCObjectPointerType(LHSType))))
3395 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003396
Chris Lattner34c85082008-08-21 18:04:13 +00003397 // If the RHS is a unary plus or minus, check to see if they = and + are
3398 // right next to each other. If so, the user may have typo'd "x =+ 4"
3399 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003400 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003401 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3402 RHSCheck = ICE->getSubExpr();
3403 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3404 if ((UO->getOpcode() == UnaryOperator::Plus ||
3405 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003406 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003407 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003408 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003409 Diag(Loc, diag::warn_not_compound_assign)
3410 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3411 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003412 }
3413 } else {
3414 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003415 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003416 }
Chris Lattner005ed752008-01-04 18:04:52 +00003417
Chris Lattner1eafdea2008-11-18 01:30:42 +00003418 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3419 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003420 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003421
Chris Lattner4b009652007-07-25 00:24:17 +00003422 // C99 6.5.16p3: The type of an assignment expression is the type of the
3423 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003424 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003425 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3426 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003427 // C++ 5.17p1: the type of the assignment expression is that of its left
3428 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003429 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003430}
3431
Chris Lattner1eafdea2008-11-18 01:30:42 +00003432// C99 6.5.17
3433QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3434 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003435
Chris Lattner03c430f2008-07-25 20:54:07 +00003436 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003437 DefaultFunctionArrayConversion(RHS);
3438 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003439}
3440
3441/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3442/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003443QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3444 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003445 QualType ResType = Op->getType();
3446 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003447
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003448 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3449 // Decrement of bool is not allowed.
3450 if (!isInc) {
3451 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3452 return QualType();
3453 }
3454 // Increment of bool sets it to true, but is deprecated.
3455 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3456 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003457 // OK!
3458 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3459 // C99 6.5.2.4p2, 6.5.6p2
3460 if (PT->getPointeeType()->isObjectType()) {
3461 // Pointer to object is ok!
3462 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003463 if (getLangOptions().CPlusPlus) {
3464 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3465 << Op->getSourceRange();
3466 return QualType();
3467 }
3468
3469 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003470 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003471 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003472 if (getLangOptions().CPlusPlus) {
3473 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3474 << Op->getType() << Op->getSourceRange();
3475 return QualType();
3476 }
3477
3478 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003479 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003480 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003481 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003482 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003483 diag::err_typecheck_arithmetic_incomplete_type,
3484 Op->getSourceRange(), SourceRange(),
3485 ResType);
3486 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003487 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003488 } else if (ResType->isComplexType()) {
3489 // C99 does not support ++/-- on complex types, we allow as an extension.
3490 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003491 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003492 } else {
3493 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003494 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003495 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003496 }
Mike Stump9afab102009-02-19 03:04:26 +00003497 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003498 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003499 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003500 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003501 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003502}
3503
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003504/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003505/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003506/// where the declaration is needed for type checking. We only need to
3507/// handle cases when the expression references a function designator
3508/// or is an lvalue. Here are some examples:
3509/// - &(x) => x
3510/// - &*****f => f for f a function designator.
3511/// - &s.xx => s
3512/// - &s.zz[1].yy -> s, if zz is an array
3513/// - *(x + 1) -> x, if x is an array
3514/// - &"123"[2] -> 0
3515/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003516static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003517 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003518 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003519 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003520 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003521 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003522 // Fields cannot be declared with a 'register' storage class.
3523 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003524 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003525 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003526 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003527 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003528 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003529
Douglas Gregord2baafd2008-10-21 16:13:35 +00003530 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003531 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003532 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003533 return 0;
3534 else
3535 return VD;
3536 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003537 case Stmt::UnaryOperatorClass: {
3538 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003539
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003540 switch(UO->getOpcode()) {
3541 case UnaryOperator::Deref: {
3542 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003543 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3544 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3545 if (!VD || VD->getType()->isPointerType())
3546 return 0;
3547 return VD;
3548 }
3549 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003550 }
3551 case UnaryOperator::Real:
3552 case UnaryOperator::Imag:
3553 case UnaryOperator::Extension:
3554 return getPrimaryDecl(UO->getSubExpr());
3555 default:
3556 return 0;
3557 }
3558 }
3559 case Stmt::BinaryOperatorClass: {
3560 BinaryOperator *BO = cast<BinaryOperator>(E);
3561
3562 // Handle cases involving pointer arithmetic. The result of an
3563 // Assign or AddAssign is not an lvalue so they can be ignored.
3564
3565 // (x + n) or (n + x) => x
3566 if (BO->getOpcode() == BinaryOperator::Add) {
3567 if (BO->getLHS()->getType()->isPointerType()) {
3568 return getPrimaryDecl(BO->getLHS());
3569 } else if (BO->getRHS()->getType()->isPointerType()) {
3570 return getPrimaryDecl(BO->getRHS());
3571 }
3572 }
3573
3574 return 0;
3575 }
Chris Lattner4b009652007-07-25 00:24:17 +00003576 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003577 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003578 case Stmt::ImplicitCastExprClass:
3579 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003580 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003581 default:
3582 return 0;
3583 }
3584}
3585
3586/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003587/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003588/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003589/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003590/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003591/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003592/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003593QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003594 if (op->isTypeDependent())
3595 return Context.DependentTy;
3596
Steve Naroff9c6c3592008-01-13 17:10:08 +00003597 if (getLangOptions().C99) {
3598 // Implement C99-only parts of addressof rules.
3599 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3600 if (uOp->getOpcode() == UnaryOperator::Deref)
3601 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3602 // (assuming the deref expression is valid).
3603 return uOp->getSubExpr()->getType();
3604 }
3605 // Technically, there should be a check for array subscript
3606 // expressions here, but the result of one is always an lvalue anyway.
3607 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003608 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003609 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003610
Chris Lattner4b009652007-07-25 00:24:17 +00003611 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003612 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3613 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003614 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3615 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003616 return QualType();
3617 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003618 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003619 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3620 if (Field->isBitField()) {
3621 Diag(OpLoc, diag::err_typecheck_address_of)
3622 << "bit-field" << op->getSourceRange();
3623 return QualType();
3624 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003625 }
3626 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003627 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3628 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003629 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003630 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003631 return QualType();
3632 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003633 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003634 // with the register storage-class specifier.
3635 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3636 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003637 Diag(OpLoc, diag::err_typecheck_address_of)
3638 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003639 return QualType();
3640 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003641 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003642 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003643 } else if (isa<FieldDecl>(dcl)) {
3644 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003645 // Could be a pointer to member, though, if there is an explicit
3646 // scope qualifier for the class.
3647 if (isa<QualifiedDeclRefExpr>(op)) {
3648 DeclContext *Ctx = dcl->getDeclContext();
3649 if (Ctx && Ctx->isRecord())
3650 return Context.getMemberPointerType(op->getType(),
3651 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3652 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003653 } else if (isa<FunctionDecl>(dcl)) {
3654 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003655 // As above.
3656 if (isa<QualifiedDeclRefExpr>(op)) {
3657 DeclContext *Ctx = dcl->getDeclContext();
3658 if (Ctx && Ctx->isRecord())
3659 return Context.getMemberPointerType(op->getType(),
3660 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3661 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003662 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003663 else
Chris Lattner4b009652007-07-25 00:24:17 +00003664 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003665 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003666
Chris Lattner4b009652007-07-25 00:24:17 +00003667 // If the operand has type "type", the result has type "pointer to type".
3668 return Context.getPointerType(op->getType());
3669}
3670
Chris Lattnerda5c0872008-11-23 09:13:29 +00003671QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3672 UsualUnaryConversions(Op);
3673 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003674
Chris Lattnerda5c0872008-11-23 09:13:29 +00003675 // Note that per both C89 and C99, this is always legal, even if ptype is an
3676 // incomplete type or void. It would be possible to warn about dereferencing
3677 // a void pointer, but it's completely well-defined, and such a warning is
3678 // unlikely to catch any mistakes.
3679 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003680 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003681
Chris Lattner77d52da2008-11-20 06:06:08 +00003682 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003683 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003684 return QualType();
3685}
3686
3687static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3688 tok::TokenKind Kind) {
3689 BinaryOperator::Opcode Opc;
3690 switch (Kind) {
3691 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003692 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3693 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003694 case tok::star: Opc = BinaryOperator::Mul; break;
3695 case tok::slash: Opc = BinaryOperator::Div; break;
3696 case tok::percent: Opc = BinaryOperator::Rem; break;
3697 case tok::plus: Opc = BinaryOperator::Add; break;
3698 case tok::minus: Opc = BinaryOperator::Sub; break;
3699 case tok::lessless: Opc = BinaryOperator::Shl; break;
3700 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3701 case tok::lessequal: Opc = BinaryOperator::LE; break;
3702 case tok::less: Opc = BinaryOperator::LT; break;
3703 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3704 case tok::greater: Opc = BinaryOperator::GT; break;
3705 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3706 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3707 case tok::amp: Opc = BinaryOperator::And; break;
3708 case tok::caret: Opc = BinaryOperator::Xor; break;
3709 case tok::pipe: Opc = BinaryOperator::Or; break;
3710 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3711 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3712 case tok::equal: Opc = BinaryOperator::Assign; break;
3713 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3714 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3715 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3716 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3717 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3718 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3719 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3720 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3721 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3722 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3723 case tok::comma: Opc = BinaryOperator::Comma; break;
3724 }
3725 return Opc;
3726}
3727
3728static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3729 tok::TokenKind Kind) {
3730 UnaryOperator::Opcode Opc;
3731 switch (Kind) {
3732 default: assert(0 && "Unknown unary op!");
3733 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3734 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3735 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3736 case tok::star: Opc = UnaryOperator::Deref; break;
3737 case tok::plus: Opc = UnaryOperator::Plus; break;
3738 case tok::minus: Opc = UnaryOperator::Minus; break;
3739 case tok::tilde: Opc = UnaryOperator::Not; break;
3740 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003741 case tok::kw___real: Opc = UnaryOperator::Real; break;
3742 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3743 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3744 }
3745 return Opc;
3746}
3747
Douglas Gregord7f915e2008-11-06 23:29:22 +00003748/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3749/// operator @p Opc at location @c TokLoc. This routine only supports
3750/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003751Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3752 unsigned Op,
3753 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003754 QualType ResultTy; // Result type of the binary operator.
3755 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3756 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3757
3758 switch (Opc) {
3759 default:
3760 assert(0 && "Unknown binary expr!");
3761 case BinaryOperator::Assign:
3762 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3763 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003764 case BinaryOperator::PtrMemD:
3765 case BinaryOperator::PtrMemI:
3766 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3767 Opc == BinaryOperator::PtrMemI);
3768 break;
3769 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003770 case BinaryOperator::Div:
3771 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3772 break;
3773 case BinaryOperator::Rem:
3774 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3775 break;
3776 case BinaryOperator::Add:
3777 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3778 break;
3779 case BinaryOperator::Sub:
3780 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3781 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003782 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003783 case BinaryOperator::Shr:
3784 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3785 break;
3786 case BinaryOperator::LE:
3787 case BinaryOperator::LT:
3788 case BinaryOperator::GE:
3789 case BinaryOperator::GT:
3790 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3791 break;
3792 case BinaryOperator::EQ:
3793 case BinaryOperator::NE:
3794 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3795 break;
3796 case BinaryOperator::And:
3797 case BinaryOperator::Xor:
3798 case BinaryOperator::Or:
3799 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3800 break;
3801 case BinaryOperator::LAnd:
3802 case BinaryOperator::LOr:
3803 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3804 break;
3805 case BinaryOperator::MulAssign:
3806 case BinaryOperator::DivAssign:
3807 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3808 if (!CompTy.isNull())
3809 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3810 break;
3811 case BinaryOperator::RemAssign:
3812 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3813 if (!CompTy.isNull())
3814 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3815 break;
3816 case BinaryOperator::AddAssign:
3817 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3818 if (!CompTy.isNull())
3819 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3820 break;
3821 case BinaryOperator::SubAssign:
3822 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3823 if (!CompTy.isNull())
3824 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3825 break;
3826 case BinaryOperator::ShlAssign:
3827 case BinaryOperator::ShrAssign:
3828 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3829 if (!CompTy.isNull())
3830 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3831 break;
3832 case BinaryOperator::AndAssign:
3833 case BinaryOperator::XorAssign:
3834 case BinaryOperator::OrAssign:
3835 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3836 if (!CompTy.isNull())
3837 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3838 break;
3839 case BinaryOperator::Comma:
3840 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3841 break;
3842 }
3843 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003844 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003845 if (CompTy.isNull())
3846 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3847 else
3848 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003849 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003850}
3851
Chris Lattner4b009652007-07-25 00:24:17 +00003852// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003853Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3854 tok::TokenKind Kind,
3855 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003856 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003857 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003858
Steve Naroff87d58b42007-09-16 03:34:24 +00003859 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3860 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003861
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003862 // If either expression is type-dependent, just build the AST.
3863 // FIXME: We'll need to perform some caching of the result of name
3864 // lookup for operator+.
3865 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003866 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3867 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003868 Context.DependentTy,
3869 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003870 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003871 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3872 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003873 }
3874
Sebastian Redl95216a62009-02-07 00:15:38 +00003875 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003876 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3877 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003878 // If this is one of the assignment operators, we only perform
3879 // overload resolution if the left-hand side is a class or
3880 // enumeration type (C++ [expr.ass]p3).
3881 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3882 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3883 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3884 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003885
Douglas Gregord7f915e2008-11-06 23:29:22 +00003886 // Determine which overloaded operator we're dealing with.
3887 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003888 // Overloading .* is not possible.
3889 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003890 OO_Star, OO_Slash, OO_Percent,
3891 OO_Plus, OO_Minus,
3892 OO_LessLess, OO_GreaterGreater,
3893 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3894 OO_EqualEqual, OO_ExclaimEqual,
3895 OO_Amp,
3896 OO_Caret,
3897 OO_Pipe,
3898 OO_AmpAmp,
3899 OO_PipePipe,
3900 OO_Equal, OO_StarEqual,
3901 OO_SlashEqual, OO_PercentEqual,
3902 OO_PlusEqual, OO_MinusEqual,
3903 OO_LessLessEqual, OO_GreaterGreaterEqual,
3904 OO_AmpEqual, OO_CaretEqual,
3905 OO_PipeEqual,
3906 OO_Comma
3907 };
3908 OverloadedOperatorKind OverOp = OverOps[Opc];
3909
Mike Stump9afab102009-02-19 03:04:26 +00003910 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003911 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003912 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003913 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003914 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3915 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003916
3917 // Perform overload resolution.
3918 OverloadCandidateSet::iterator Best;
3919 switch (BestViableFunction(CandidateSet, Best)) {
3920 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003921 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003922 FunctionDecl *FnDecl = Best->Function;
3923
Douglas Gregor70d26122008-11-12 17:17:38 +00003924 if (FnDecl) {
3925 // We matched an overloaded operator. Build a call to that
3926 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003927
Douglas Gregor70d26122008-11-12 17:17:38 +00003928 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3930 if (PerformObjectArgumentInitialization(lhs, Method) ||
3931 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3932 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003933 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003934 } else {
3935 // Convert the arguments.
3936 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3937 "passing") ||
3938 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3939 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003940 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003941 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003942
Douglas Gregor70d26122008-11-12 17:17:38 +00003943 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003944 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003945 = FnDecl->getType()->getAsFunctionType()->getResultType();
3946 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003947
Douglas Gregor70d26122008-11-12 17:17:38 +00003948 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003949 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3950 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003951 UsualUnaryConversions(FnExpr);
3952
Mike Stump9afab102009-02-19 03:04:26 +00003953 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003954 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003955 } else {
3956 // We matched a built-in operator. Convert the arguments, then
3957 // break out so that we will build the appropriate built-in
3958 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003959 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3960 Best->Conversions[0], "passing") ||
3961 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3962 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003963 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003964
3965 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003966 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003967 }
3968
3969 case OR_No_Viable_Function:
3970 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003971 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003972 break;
3973
3974 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003975 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3976 << BinaryOperator::getOpcodeStr(Opc)
3977 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003978 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003979 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00003980
3981 case OR_Deleted:
3982 Diag(TokLoc, diag::err_ovl_deleted_oper)
3983 << Best->Function->isDeleted()
3984 << BinaryOperator::getOpcodeStr(Opc)
3985 << lhs->getSourceRange() << rhs->getSourceRange();
3986 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3987 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003988 }
3989
Douglas Gregor70d26122008-11-12 17:17:38 +00003990 // Either we found no viable overloaded operator or we matched a
3991 // built-in operator. In either case, fall through to trying to
3992 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003993 }
3994
Douglas Gregord7f915e2008-11-06 23:29:22 +00003995 // Build a built-in binary operation.
3996 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003997}
3998
3999// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00004000Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4001 tok::TokenKind Op, ExprArg input) {
4002 // FIXME: Input is modified later, but smart pointer not reassigned.
4003 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004004 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004005
4006 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00004007 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004008 || Input->getType()->isEnumeralType())) {
4009 // Determine which overloaded operator we're dealing with.
4010 static const OverloadedOperatorKind OverOps[] = {
4011 OO_None, OO_None,
4012 OO_PlusPlus, OO_MinusMinus,
4013 OO_Amp, OO_Star,
4014 OO_Plus, OO_Minus,
4015 OO_Tilde, OO_Exclaim,
4016 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004017 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004018 OO_None
4019 };
4020 OverloadedOperatorKind OverOp = OverOps[Opc];
4021
Mike Stump9afab102009-02-19 03:04:26 +00004022 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004023 // to the candidate set.
4024 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004025 if (OverOp != OO_None &&
4026 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4027 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004028
4029 // Perform overload resolution.
4030 OverloadCandidateSet::iterator Best;
4031 switch (BestViableFunction(CandidateSet, Best)) {
4032 case OR_Success: {
4033 // We found a built-in operator or an overloaded operator.
4034 FunctionDecl *FnDecl = Best->Function;
4035
4036 if (FnDecl) {
4037 // We matched an overloaded operator. Build a call to that
4038 // operator.
4039
4040 // Convert the arguments.
4041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4042 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004043 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004044 } else {
4045 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004046 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004047 FnDecl->getParamDecl(0)->getType(),
4048 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004049 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004050 }
4051
4052 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004053 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004054 = FnDecl->getType()->getAsFunctionType()->getResultType();
4055 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004056
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004057 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004058 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004059 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004060 UsualUnaryConversions(FnExpr);
4061
Sebastian Redl8b769972009-01-19 00:08:26 +00004062 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004063 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4064 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004065 } else {
4066 // We matched a built-in operator. Convert the arguments, then
4067 // break out so that we will build the appropriate built-in
4068 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004069 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4070 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004071 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004072
4073 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004074 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004075 }
4076
4077 case OR_No_Viable_Function:
4078 // No viable function; fall through to handling this as a
4079 // built-in operator, which will produce an error message for us.
4080 break;
4081
4082 case OR_Ambiguous:
4083 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4084 << UnaryOperator::getOpcodeStr(Opc)
4085 << Input->getSourceRange();
4086 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004087 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004088
4089 case OR_Deleted:
4090 Diag(OpLoc, diag::err_ovl_deleted_oper)
4091 << Best->Function->isDeleted()
4092 << UnaryOperator::getOpcodeStr(Opc)
4093 << Input->getSourceRange();
4094 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4095 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004096 }
4097
4098 // Either we found no viable overloaded operator or we matched a
4099 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004100 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004101 }
4102
Chris Lattner4b009652007-07-25 00:24:17 +00004103 QualType resultType;
4104 switch (Opc) {
4105 default:
4106 assert(0 && "Unimplemented unary expr!");
4107 case UnaryOperator::PreInc:
4108 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004109 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4110 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004111 break;
Mike Stump9afab102009-02-19 03:04:26 +00004112 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004113 resultType = CheckAddressOfOperand(Input, OpLoc);
4114 break;
Mike Stump9afab102009-02-19 03:04:26 +00004115 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004116 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004117 resultType = CheckIndirectionOperand(Input, OpLoc);
4118 break;
4119 case UnaryOperator::Plus:
4120 case UnaryOperator::Minus:
4121 UsualUnaryConversions(Input);
4122 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004123 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4124 break;
4125 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4126 resultType->isEnumeralType())
4127 break;
4128 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4129 Opc == UnaryOperator::Plus &&
4130 resultType->isPointerType())
4131 break;
4132
Sebastian Redl8b769972009-01-19 00:08:26 +00004133 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4134 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004135 case UnaryOperator::Not: // bitwise complement
4136 UsualUnaryConversions(Input);
4137 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004138 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4139 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4140 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004141 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004142 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004143 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004144 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4145 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004146 break;
4147 case UnaryOperator::LNot: // logical negation
4148 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4149 DefaultFunctionArrayConversion(Input);
4150 resultType = Input->getType();
4151 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004152 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4153 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004154 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004155 // In C++, it's bool. C++ 5.3.1p8
4156 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004157 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004158 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004159 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004160 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004161 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004162 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004163 resultType = Input->getType();
4164 break;
4165 }
4166 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004167 return ExprError();
4168 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004169 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004170}
4171
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004172/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004173Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004174 SourceLocation LabLoc,
4175 IdentifierInfo *LabelII) {
4176 // Look up the record for this label identifier.
4177 LabelStmt *&LabelDecl = LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004178
Daniel Dunbar879788d2008-08-04 16:51:22 +00004179 // If we haven't seen this label yet, create a forward reference. It
4180 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004181 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004182 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004183
Chris Lattner4b009652007-07-25 00:24:17 +00004184 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004185 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4186 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004187}
4188
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004189Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004190 SourceLocation RPLoc) { // "({..})"
4191 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4192 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4193 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4194
Eli Friedmanbc941e12009-01-24 23:09:00 +00004195 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4196 if (isFileScope) {
4197 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4198 }
4199
Chris Lattner4b009652007-07-25 00:24:17 +00004200 // FIXME: there are a variety of strange constraints to enforce here, for
4201 // example, it is not possible to goto into a stmt expression apparently.
4202 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004203
Chris Lattner4b009652007-07-25 00:24:17 +00004204 // FIXME: the last statement in the compount stmt has its value used. We
4205 // should not warn about it being unused.
4206
4207 // If there are sub stmts in the compound stmt, take the type of the last one
4208 // as the type of the stmtexpr.
4209 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004210
Chris Lattner200964f2008-07-26 19:51:01 +00004211 if (!Compound->body_empty()) {
4212 Stmt *LastStmt = Compound->body_back();
4213 // If LastStmt is a label, skip down through into the body.
4214 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4215 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004216
Chris Lattner200964f2008-07-26 19:51:01 +00004217 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004218 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004219 }
Mike Stump9afab102009-02-19 03:04:26 +00004220
Steve Naroff774e4152009-01-21 00:14:39 +00004221 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004222}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004223
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004224Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4225 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004226 SourceLocation TypeLoc,
4227 TypeTy *argty,
4228 OffsetOfComponent *CompPtr,
4229 unsigned NumComponents,
4230 SourceLocation RPLoc) {
4231 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4232 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004233
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004234 // We must have at least one component that refers to the type, and the first
4235 // one is known to be a field designator. Verify that the ArgTy represents
4236 // a struct/union/class.
4237 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004238 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004239
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004240 // Otherwise, create a compound literal expression as the base, and
4241 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004242 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004243 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004244 IList->setType(ArgTy);
4245 Expr *Res =
4246 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4247
Chris Lattnerb37522e2007-08-31 21:49:13 +00004248 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4249 // GCC extension, diagnose them.
4250 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004251 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4252 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004253
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004254 for (unsigned i = 0; i != NumComponents; ++i) {
4255 const OffsetOfComponent &OC = CompPtr[i];
4256 if (OC.isBrackets) {
4257 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004258 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004259 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004260 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004261 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004262 }
Mike Stump9afab102009-02-19 03:04:26 +00004263
Chris Lattner2af6a802007-08-30 17:59:59 +00004264 // FIXME: C++: Verify that operator[] isn't overloaded.
4265
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004266 // C99 6.5.2.1p1
4267 Expr *Idx = static_cast<Expr*>(OC.U.E);
4268 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004269 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4270 << Idx->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004271
4272 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004273 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004274 continue;
4275 }
Mike Stump9afab102009-02-19 03:04:26 +00004276
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004277 const RecordType *RC = Res->getType()->getAsRecordType();
4278 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004279 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004280 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004281 }
Mike Stump9afab102009-02-19 03:04:26 +00004282
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004283 // Get the decl corresponding to this.
4284 RecordDecl *RD = RC->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00004285 FieldDecl *MemberDecl
4286 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004287 LookupMemberName)
4288 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004289 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004290 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4291 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004292
Chris Lattner2af6a802007-08-30 17:59:59 +00004293 // FIXME: C++: Verify that MemberDecl isn't a static field.
4294 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004295 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4296 // matter here.
Mike Stump9afab102009-02-19 03:04:26 +00004297 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004298 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004299 }
Mike Stump9afab102009-02-19 03:04:26 +00004300
4301 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004302 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004303}
4304
4305
Mike Stump9afab102009-02-19 03:04:26 +00004306Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004307 TypeTy *arg1, TypeTy *arg2,
4308 SourceLocation RPLoc) {
4309 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4310 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004311
Steve Naroff63bad2d2007-08-01 22:05:33 +00004312 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004313
4314 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004315 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004316}
4317
Mike Stump9afab102009-02-19 03:04:26 +00004318Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004319 ExprTy *expr1, ExprTy *expr2,
4320 SourceLocation RPLoc) {
4321 Expr *CondExpr = static_cast<Expr*>(cond);
4322 Expr *LHSExpr = static_cast<Expr*>(expr1);
4323 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004324
Steve Naroff93c53012007-08-03 21:21:27 +00004325 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4326
4327 // The conditional expression is required to be a constant expression.
4328 llvm::APSInt condEval(32);
4329 SourceLocation ExpLoc;
4330 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004331 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4332 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004333
4334 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Mike Stump9afab102009-02-19 03:04:26 +00004335 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
Steve Naroff93c53012007-08-03 21:21:27 +00004336 RHSExpr->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004337 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004338 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004339}
4340
Steve Naroff52a81c02008-09-03 18:15:37 +00004341//===----------------------------------------------------------------------===//
4342// Clang Extensions.
4343//===----------------------------------------------------------------------===//
4344
4345/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004346void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004347 // Analyze block parameters.
4348 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004349
Steve Naroff52a81c02008-09-03 18:15:37 +00004350 // Add BSI to CurBlock.
4351 BSI->PrevBlockInfo = CurBlock;
4352 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004353
Steve Naroff52a81c02008-09-03 18:15:37 +00004354 BSI->ReturnType = 0;
4355 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004356 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004357
Steve Naroff52059382008-10-10 01:28:17 +00004358 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004359 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004360}
4361
Mike Stumpc1fddff2009-02-04 22:31:32 +00004362void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4363 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4364
4365 if (ParamInfo.getNumTypeObjects() == 0
4366 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4367 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4368
4369 // The type is entirely optional as well, if none, use DependentTy.
4370 if (T.isNull())
4371 T = Context.DependentTy;
4372
4373 // The parameter list is optional, if there was none, assume ().
4374 if (!T->isFunctionType())
4375 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4376
4377 CurBlock->hasPrototype = true;
4378 CurBlock->isVariadic = false;
4379 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4380 .getTypePtr();
4381
4382 if (!RetTy->isDependentType())
4383 CurBlock->ReturnType = RetTy;
4384 return;
4385 }
4386
Steve Naroff52a81c02008-09-03 18:15:37 +00004387 // Analyze arguments to block.
4388 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4389 "Not a function declarator!");
4390 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004391
Steve Naroff52059382008-10-10 01:28:17 +00004392 CurBlock->hasPrototype = FTI.hasPrototype;
4393 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004394
Steve Naroff52a81c02008-09-03 18:15:37 +00004395 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4396 // no arguments, not a function that takes a single void argument.
4397 if (FTI.hasPrototype &&
4398 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4399 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4400 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4401 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004402 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004403 } else if (FTI.hasPrototype) {
4404 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004405 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4406 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004407 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4408
4409 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4410 .getTypePtr();
4411
4412 if (!RetTy->isDependentType())
4413 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004414 }
Steve Naroff52059382008-10-10 01:28:17 +00004415 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004416
Steve Naroff52059382008-10-10 01:28:17 +00004417 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4418 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4419 // If this has an identifier, add it to the scope stack.
4420 if ((*AI)->getIdentifier())
4421 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004422}
4423
4424/// ActOnBlockError - If there is an error parsing a block, this callback
4425/// is invoked to pop the information about the block from the action impl.
4426void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4427 // Ensure that CurBlock is deleted.
4428 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004429
Steve Naroff52a81c02008-09-03 18:15:37 +00004430 // Pop off CurBlock, handle nested blocks.
4431 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004432
Steve Naroff52a81c02008-09-03 18:15:37 +00004433 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004434
Steve Naroff52a81c02008-09-03 18:15:37 +00004435}
4436
4437/// ActOnBlockStmtExpr - This is called when the body of a block statement
4438/// literal was successfully completed. ^(int x){...}
4439Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4440 Scope *CurScope) {
4441 // Ensure that CurBlock is deleted.
4442 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004443 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004444
Steve Naroff52059382008-10-10 01:28:17 +00004445 PopDeclContext();
4446
Steve Naroff52a81c02008-09-03 18:15:37 +00004447 // Pop off CurBlock, handle nested blocks.
4448 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004449
Steve Naroff52a81c02008-09-03 18:15:37 +00004450 QualType RetTy = Context.VoidTy;
4451 if (BSI->ReturnType)
4452 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004453
Steve Naroff52a81c02008-09-03 18:15:37 +00004454 llvm::SmallVector<QualType, 8> ArgTypes;
4455 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4456 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004457
Steve Naroff52a81c02008-09-03 18:15:37 +00004458 QualType BlockTy;
4459 if (!BSI->hasPrototype)
4460 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4461 else
4462 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004463 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004464
Steve Naroff52a81c02008-09-03 18:15:37 +00004465 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004466
Steve Naroff95029d92008-10-08 18:44:00 +00004467 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004468 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004469}
4470
Anders Carlsson36760332007-10-15 20:28:48 +00004471Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4472 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004473 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004474 Expr *E = static_cast<Expr*>(expr);
4475 QualType T = QualType::getFromOpaquePtr(type);
4476
4477 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004478
4479 // Get the va_list type
4480 QualType VaListType = Context.getBuiltinVaListType();
4481 // Deal with implicit array decay; for example, on x86-64,
4482 // va_list is an array, but it's supposed to decay to
4483 // a pointer for va_arg.
4484 if (VaListType->isArrayType())
4485 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004486 // Make sure the input expression also decays appropriately.
4487 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004488
4489 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004490 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004491 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004492 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004493
Anders Carlsson36760332007-10-15 20:28:48 +00004494 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004495
Steve Naroff774e4152009-01-21 00:14:39 +00004496 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004497}
4498
Douglas Gregorad4b3792008-11-29 04:51:27 +00004499Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4500 // The type of __null will be int or long, depending on the size of
4501 // pointers on the target.
4502 QualType Ty;
4503 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4504 Ty = Context.IntTy;
4505 else
4506 Ty = Context.LongTy;
4507
Steve Naroff774e4152009-01-21 00:14:39 +00004508 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004509}
4510
Chris Lattner005ed752008-01-04 18:04:52 +00004511bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4512 SourceLocation Loc,
4513 QualType DstType, QualType SrcType,
4514 Expr *SrcExpr, const char *Flavor) {
4515 // Decode the result (notice that AST's are still created for extensions).
4516 bool isInvalid = false;
4517 unsigned DiagKind;
4518 switch (ConvTy) {
4519 default: assert(0 && "Unknown conversion type");
4520 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004521 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004522 DiagKind = diag::ext_typecheck_convert_pointer_int;
4523 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004524 case IntToPointer:
4525 DiagKind = diag::ext_typecheck_convert_int_pointer;
4526 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004527 case IncompatiblePointer:
4528 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4529 break;
4530 case FunctionVoidPointer:
4531 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4532 break;
4533 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004534 // If the qualifiers lost were because we were applying the
4535 // (deprecated) C++ conversion from a string literal to a char*
4536 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4537 // Ideally, this check would be performed in
4538 // CheckPointerTypesForAssignment. However, that would require a
4539 // bit of refactoring (so that the second argument is an
4540 // expression, rather than a type), which should be done as part
4541 // of a larger effort to fix CheckPointerTypesForAssignment for
4542 // C++ semantics.
4543 if (getLangOptions().CPlusPlus &&
4544 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4545 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004546 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4547 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004548 case IntToBlockPointer:
4549 DiagKind = diag::err_int_to_block_pointer;
4550 break;
4551 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004552 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004553 break;
Steve Naroff19608432008-10-14 22:18:38 +00004554 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004555 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004556 // it can give a more specific diagnostic.
4557 DiagKind = diag::warn_incompatible_qualified_id;
4558 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004559 case IncompatibleVectors:
4560 DiagKind = diag::warn_incompatible_vectors;
4561 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004562 case Incompatible:
4563 DiagKind = diag::err_typecheck_convert_incompatible;
4564 isInvalid = true;
4565 break;
4566 }
Mike Stump9afab102009-02-19 03:04:26 +00004567
Chris Lattner271d4c22008-11-24 05:29:24 +00004568 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4569 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004570 return isInvalid;
4571}
Anders Carlssond5201b92008-11-30 19:50:32 +00004572
4573bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4574{
4575 Expr::EvalResult EvalResult;
4576
Mike Stump9afab102009-02-19 03:04:26 +00004577 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004578 EvalResult.HasSideEffects) {
4579 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4580
4581 if (EvalResult.Diag) {
4582 // We only show the note if it's not the usual "invalid subexpression"
4583 // or if it's actually in a subexpression.
4584 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4585 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4586 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4587 }
Mike Stump9afab102009-02-19 03:04:26 +00004588
Anders Carlssond5201b92008-11-30 19:50:32 +00004589 return true;
4590 }
4591
4592 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004593 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004594 E->getSourceRange();
4595
4596 // Print the reason it's not a constant.
4597 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4598 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4599 }
Mike Stump9afab102009-02-19 03:04:26 +00004600
Anders Carlssond5201b92008-11-30 19:50:32 +00004601 if (Result)
4602 *Result = EvalResult.Val.getInt();
4603 return false;
4604}