blob: 174e408ead460ef613ca1605f45d575e9c08bd52 [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 }
876 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000877
878 // Only create DeclRefExpr's for valid Decl's.
879 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000880 return ExprError();
881
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000882 // If the identifier reference is inside a block, and it refers to a value
883 // that is outside the block, create a BlockDeclRefExpr instead of a
884 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
885 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000886 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000887 // We do not do this for things like enum constants, global variables, etc,
888 // as they do not get snapshotted.
889 //
890 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000891 // Blocks that have these can't be constant.
892 CurBlock->hasBlockDeclRefExprs = true;
893
Steve Naroff52059382008-10-10 01:28:17 +0000894 // The BlocksAttr indicates the variable is bound by-reference.
895 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000896 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000897 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000898
Steve Naroff52059382008-10-10 01:28:17 +0000899 // Variable will be bound by-copy, make it const within the closure.
900 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000901 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000902 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000903 }
904 // If this reference is not in a block or if the referenced variable is
905 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000906
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000907 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000908 bool ValueDependent = false;
909 if (getLangOptions().CPlusPlus) {
910 // C++ [temp.dep.expr]p3:
911 // An id-expression is type-dependent if it contains:
912 // - an identifier that was declared with a dependent type,
913 if (VD->getType()->isDependentType())
914 TypeDependent = true;
915 // - FIXME: a template-id that is dependent,
916 // - a conversion-function-id that specifies a dependent type,
917 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
918 Name.getCXXNameType()->isDependentType())
919 TypeDependent = true;
920 // - a nested-name-specifier that contains a class-name that
921 // names a dependent type.
922 else if (SS && !SS->isEmpty()) {
923 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
924 DC; DC = DC->getParent()) {
925 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000926 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000927 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
928 if (Context.getTypeDeclType(Record)->isDependentType()) {
929 TypeDependent = true;
930 break;
931 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000932 }
933 }
934 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000935
Douglas Gregora5d84612008-12-10 20:57:37 +0000936 // C++ [temp.dep.constexpr]p2:
937 //
938 // An identifier is value-dependent if it is:
939 // - a name declared with a dependent type,
940 if (TypeDependent)
941 ValueDependent = true;
942 // - the name of a non-type template parameter,
943 else if (isa<NonTypeTemplateParmDecl>(VD))
944 ValueDependent = true;
945 // - a constant with integral or enumeration type and is
946 // initialized with an expression that is value-dependent
947 // (FIXME!).
948 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000949
Sebastian Redlcd883f72009-01-18 18:53:16 +0000950 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
951 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000952}
953
Sebastian Redlcd883f72009-01-18 18:53:16 +0000954Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
955 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000956 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000957
Chris Lattner4b009652007-07-25 00:24:17 +0000958 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000959 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000960 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
961 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
962 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000963 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000964
Chris Lattner7e637512008-01-12 08:14:25 +0000965 // Pre-defined identifiers are of type char[x], where x is the length of the
966 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000967 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000968 if (FunctionDecl *FD = getCurFunctionDecl())
969 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000970 else if (ObjCMethodDecl *MD = getCurMethodDecl())
971 Length = MD->getSynthesizedMethodSize();
972 else {
973 Diag(Loc, diag::ext_predef_outside_function);
974 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
975 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
976 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000977
978
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000979 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000980 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000981 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000982 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000983}
984
Sebastian Redlcd883f72009-01-18 18:53:16 +0000985Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000986 llvm::SmallString<16> CharBuffer;
987 CharBuffer.resize(Tok.getLength());
988 const char *ThisTokBegin = &CharBuffer[0];
989 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
Chris Lattner4b009652007-07-25 00:24:17 +0000991 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
992 Tok.getLocation(), PP);
993 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000995
996 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
997
Sebastian Redl75324932009-01-20 22:23:13 +0000998 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
999 Literal.isWide(),
1000 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001001}
1002
Sebastian Redlcd883f72009-01-18 18:53:16 +00001003Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1004 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001005 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1006 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001007 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001008 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001009 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001010 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001011 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001012
Chris Lattner4b009652007-07-25 00:24:17 +00001013 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001014 // Add padding so that NumericLiteralParser can overread by one character.
1015 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001016 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001017
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // Get the spelling of the token, which eliminates trigraphs, etc.
1019 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001020
Chris Lattner4b009652007-07-25 00:24:17 +00001021 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1022 Tok.getLocation(), PP);
1023 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001024 return ExprError();
1025
Chris Lattner1de66eb2007-08-26 03:42:43 +00001026 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001027
Chris Lattner1de66eb2007-08-26 03:42:43 +00001028 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001029 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001030 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001031 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001032 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001033 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001034 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001035 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001036
1037 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1038
Ted Kremenekddedbe22007-11-29 00:56:49 +00001039 // isExact will be set by GetFloatValue().
1040 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001041 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1042 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043
Chris Lattner1de66eb2007-08-26 03:42:43 +00001044 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001045 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001046 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001047 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001048
Neil Booth7421e9c2007-08-29 22:00:19 +00001049 // long long is a C99 feature.
1050 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001051 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001052 Diag(Tok.getLocation(), diag::ext_longlong);
1053
Chris Lattner4b009652007-07-25 00:24:17 +00001054 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001055 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001056
Chris Lattner4b009652007-07-25 00:24:17 +00001057 if (Literal.GetIntegerValue(ResultVal)) {
1058 // If this value didn't fit into uintmax_t, warn and force to ull.
1059 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001060 Ty = Context.UnsignedLongLongTy;
1061 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001062 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001063 } else {
1064 // If this value fits into a ULL, try to figure out what else it fits into
1065 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001066
Chris Lattner4b009652007-07-25 00:24:17 +00001067 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1068 // be an unsigned int.
1069 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1070
1071 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001072 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001073 if (!Literal.isLong && !Literal.isLongLong) {
1074 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001075 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001076
Chris Lattner4b009652007-07-25 00:24:17 +00001077 // Does it fit in a unsigned int?
1078 if (ResultVal.isIntN(IntSize)) {
1079 // Does it fit in a signed int?
1080 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001081 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001082 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001083 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001084 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001085 }
Chris Lattner4b009652007-07-25 00:24:17 +00001086 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001087
Chris Lattner4b009652007-07-25 00:24:17 +00001088 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001089 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001090 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001091
Chris Lattner4b009652007-07-25 00:24:17 +00001092 // Does it fit in a unsigned long?
1093 if (ResultVal.isIntN(LongSize)) {
1094 // Does it fit in a signed long?
1095 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001096 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001097 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001098 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001099 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001100 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001101 }
1102
Chris Lattner4b009652007-07-25 00:24:17 +00001103 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001104 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001105 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001106
Chris Lattner4b009652007-07-25 00:24:17 +00001107 // Does it fit in a unsigned long long?
1108 if (ResultVal.isIntN(LongLongSize)) {
1109 // Does it fit in a signed long long?
1110 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001111 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001112 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001113 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001114 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001115 }
1116 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001117
Chris Lattner4b009652007-07-25 00:24:17 +00001118 // If we still couldn't decide a type, we probably have something that
1119 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001120 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001121 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001122 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001123 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001124 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001125
Chris Lattnere4068872008-05-09 05:59:00 +00001126 if (ResultVal.getBitWidth() != Width)
1127 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001128 }
Sebastian Redl75324932009-01-20 22:23:13 +00001129 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001130 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001131
Chris Lattner1de66eb2007-08-26 03:42:43 +00001132 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1133 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001134 Res = new (Context) ImaginaryLiteral(Res,
1135 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001136
1137 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001138}
1139
Sebastian Redlcd883f72009-01-18 18:53:16 +00001140Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1141 SourceLocation R, ExprArg Val) {
1142 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001143 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001144 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001145}
1146
1147/// The UsualUnaryConversions() function is *not* called by this routine.
1148/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001149bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1150 SourceLocation OpLoc,
1151 const SourceRange &ExprRange,
1152 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001153 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001154 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001155 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001156 if (isSizeof)
1157 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1158 return false;
1159 }
1160
1161 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001162 Diag(OpLoc, diag::ext_sizeof_void_type)
1163 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001164 return false;
1165 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001166
Chris Lattner159fe082009-01-24 19:46:37 +00001167 return DiagnoseIncompleteType(OpLoc, exprType,
1168 isSizeof ? diag::err_sizeof_incomplete_type :
1169 diag::err_alignof_incomplete_type,
1170 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001171}
1172
Chris Lattner8d9f7962009-01-24 20:17:12 +00001173bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1174 const SourceRange &ExprRange) {
1175 E = E->IgnoreParens();
1176
1177 // alignof decl is always ok.
1178 if (isa<DeclRefExpr>(E))
1179 return false;
1180
1181 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1182 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1183 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001184 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001185 return true;
1186 }
1187 // Other fields are ok.
1188 return false;
1189 }
1190 }
1191 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1192}
1193
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001194/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1195/// the same for @c alignof and @c __alignof
1196/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001197Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001198Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1199 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001200 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001201 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001202
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001203 QualType ArgTy;
1204 SourceRange Range;
1205 if (isType) {
1206 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1207 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001208
1209 // Verify that the operand is valid.
1210 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1211 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001212 } else {
1213 // Get the end location.
1214 Expr *ArgEx = (Expr *)TyOrEx;
1215 Range = ArgEx->getSourceRange();
1216 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001217
1218 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001219 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001220 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001221 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001222 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1223 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1224 isInvalid = true;
1225 } else {
1226 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1227 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001228
1229 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001230 DeleteExpr(ArgEx);
1231 return ExprError();
1232 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001233 }
1234
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001235 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001236 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001237 Context.getSizeType(), OpLoc,
1238 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001239}
1240
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001241QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Chris Lattner03931a72007-08-24 21:16:53 +00001242 DefaultFunctionArrayConversion(V);
1243
Chris Lattnera16e42d2007-08-26 05:39:26 +00001244 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001245 if (const ComplexType *CT = V->getType()->getAsComplexType())
1246 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001247
1248 // Otherwise they pass through real integer and floating point types here.
1249 if (V->getType()->isArithmeticType())
1250 return V->getType();
1251
1252 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001253 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1254 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001255 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001256}
1257
1258
Chris Lattner4b009652007-07-25 00:24:17 +00001259
Sebastian Redl8b769972009-01-19 00:08:26 +00001260Action::OwningExprResult
1261Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1262 tok::TokenKind Kind, ExprArg Input) {
1263 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001264
Chris Lattner4b009652007-07-25 00:24:17 +00001265 UnaryOperator::Opcode Opc;
1266 switch (Kind) {
1267 default: assert(0 && "Unknown unary op!");
1268 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1269 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1270 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001271
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001272 if (getLangOptions().CPlusPlus &&
1273 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1274 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001275 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001276 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1277
1278 // C++ [over.inc]p1:
1279 //
1280 // [...] If the function is a member function with one
1281 // parameter (which shall be of type int) or a non-member
1282 // function with two parameters (the second of which shall be
1283 // of type int), it defines the postfix increment operator ++
1284 // for objects of that type. When the postfix increment is
1285 // called as a result of using the ++ operator, the int
1286 // argument will have value zero.
1287 Expr *Args[2] = {
1288 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001289 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1290 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001291 };
1292
1293 // Build the candidate set for overloading
1294 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001295 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1296 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001297
1298 // Perform overload resolution.
1299 OverloadCandidateSet::iterator Best;
1300 switch (BestViableFunction(CandidateSet, Best)) {
1301 case OR_Success: {
1302 // We found a built-in operator or an overloaded operator.
1303 FunctionDecl *FnDecl = Best->Function;
1304
1305 if (FnDecl) {
1306 // We matched an overloaded operator. Build a call to that
1307 // operator.
1308
1309 // Convert the arguments.
1310 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1311 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001312 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001313 } else {
1314 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001315 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001316 FnDecl->getParamDecl(0)->getType(),
1317 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001318 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001319 }
1320
1321 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001322 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001323 = FnDecl->getType()->getAsFunctionType()->getResultType();
1324 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001325
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001326 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001327 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001328 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001329 UsualUnaryConversions(FnExpr);
1330
Sebastian Redl8b769972009-01-19 00:08:26 +00001331 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001332 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1333 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001334 } else {
1335 // We matched a built-in operator. Convert the arguments, then
1336 // break out so that we will build the appropriate built-in
1337 // operator node.
1338 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1339 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001340 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001341
1342 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001343 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001344 }
1345
1346 case OR_No_Viable_Function:
1347 // No viable function; fall through to handling this as a
1348 // built-in operator, which will produce an error message for us.
1349 break;
1350
1351 case OR_Ambiguous:
1352 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1353 << UnaryOperator::getOpcodeStr(Opc)
1354 << Arg->getSourceRange();
1355 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001356 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001357
1358 case OR_Deleted:
1359 Diag(OpLoc, diag::err_ovl_deleted_oper)
1360 << Best->Function->isDeleted()
1361 << UnaryOperator::getOpcodeStr(Opc)
1362 << Arg->getSourceRange();
1363 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1364 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001365 }
1366
1367 // Either we found no viable overloaded operator or we matched a
1368 // built-in operator. In either case, fall through to trying to
1369 // build a built-in operation.
1370 }
1371
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001372 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1373 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001374 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001375 return ExprError();
1376 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001377 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001378}
1379
Sebastian Redl8b769972009-01-19 00:08:26 +00001380Action::OwningExprResult
1381Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1382 ExprArg Idx, SourceLocation RLoc) {
1383 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1384 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001385
Douglas Gregor80723c52008-11-19 17:17:41 +00001386 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001387 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001388 LHSExp->getType()->isEnumeralType() ||
1389 RHSExp->getType()->isRecordType() ||
1390 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001391 // Add the appropriate overloaded operators (C++ [over.match.oper])
1392 // to the candidate set.
1393 OverloadCandidateSet CandidateSet;
1394 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001395 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1396 SourceRange(LLoc, RLoc)))
1397 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001398
Douglas Gregor80723c52008-11-19 17:17:41 +00001399 // Perform overload resolution.
1400 OverloadCandidateSet::iterator Best;
1401 switch (BestViableFunction(CandidateSet, Best)) {
1402 case OR_Success: {
1403 // We found a built-in operator or an overloaded operator.
1404 FunctionDecl *FnDecl = Best->Function;
1405
1406 if (FnDecl) {
1407 // We matched an overloaded operator. Build a call to that
1408 // operator.
1409
1410 // Convert the arguments.
1411 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1412 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1413 PerformCopyInitialization(RHSExp,
1414 FnDecl->getParamDecl(0)->getType(),
1415 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001416 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001417 } else {
1418 // Convert the arguments.
1419 if (PerformCopyInitialization(LHSExp,
1420 FnDecl->getParamDecl(0)->getType(),
1421 "passing") ||
1422 PerformCopyInitialization(RHSExp,
1423 FnDecl->getParamDecl(1)->getType(),
1424 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001425 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001426 }
1427
1428 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001429 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001430 = FnDecl->getType()->getAsFunctionType()->getResultType();
1431 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001432
Douglas Gregor80723c52008-11-19 17:17:41 +00001433 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001434 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1435 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001436 UsualUnaryConversions(FnExpr);
1437
Sebastian Redl8b769972009-01-19 00:08:26 +00001438 Base.release();
1439 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001440 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001441 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001442 } else {
1443 // We matched a built-in operator. Convert the arguments, then
1444 // break out so that we will build the appropriate built-in
1445 // operator node.
1446 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1447 "passing") ||
1448 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1449 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001450 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001451
1452 break;
1453 }
1454 }
1455
1456 case OR_No_Viable_Function:
1457 // No viable function; fall through to handling this as a
1458 // built-in operator, which will produce an error message for us.
1459 break;
1460
1461 case OR_Ambiguous:
1462 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1463 << "[]"
1464 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1465 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001466 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001467
1468 case OR_Deleted:
1469 Diag(LLoc, diag::err_ovl_deleted_oper)
1470 << Best->Function->isDeleted()
1471 << "[]"
1472 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1473 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1474 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001475 }
1476
1477 // Either we found no viable overloaded operator or we matched a
1478 // built-in operator. In either case, fall through to trying to
1479 // build a built-in operation.
1480 }
1481
Chris Lattner4b009652007-07-25 00:24:17 +00001482 // Perform default conversions.
1483 DefaultFunctionArrayConversion(LHSExp);
1484 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001485
Chris Lattner4b009652007-07-25 00:24:17 +00001486 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1487
1488 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001489 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001490 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001491 // and index from the expression types.
1492 Expr *BaseExpr, *IndexExpr;
1493 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001494 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001495 BaseExpr = LHSExp;
1496 IndexExpr = RHSExp;
1497 // FIXME: need to deal with const...
1498 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001499 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001500 // Handle the uncommon case of "123[Ptr]".
1501 BaseExpr = RHSExp;
1502 IndexExpr = LHSExp;
1503 // FIXME: need to deal with const...
1504 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001505 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1506 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001507 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001508
Chris Lattner4b009652007-07-25 00:24:17 +00001509 // FIXME: need to deal with const...
1510 ResultType = VTy->getElementType();
1511 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001512 return ExprError(Diag(LHSExp->getLocStart(),
1513 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1514 }
Chris Lattner4b009652007-07-25 00:24:17 +00001515 // C99 6.5.2.1p1
1516 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001517 return ExprError(Diag(IndexExpr->getLocStart(),
1518 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001519
1520 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1521 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001522 // void (*)(int)) and pointers to incomplete types. Functions are not
1523 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001524 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001525 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001526 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001527 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001528
Sebastian Redl8b769972009-01-19 00:08:26 +00001529 Base.release();
1530 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001531 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001532 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001533}
1534
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001535QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001536CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001537 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001538 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001539
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001540 // The vector accessor can't exceed the number of elements.
1541 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001542
Mike Stump9afab102009-02-19 03:04:26 +00001543 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001544 // special names that indicate a subset of exactly half the elements are
1545 // to be selected.
1546 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001547
Nate Begeman1486b502009-01-18 01:47:54 +00001548 // This flag determines whether or not CompName has an 's' char prefix,
1549 // indicating that it is a string of hex values to be used as vector indices.
1550 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001551
1552 // Check that we've found one of the special components, or that the component
1553 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001554 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001555 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1556 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001557 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001558 do
1559 compStr++;
1560 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001561 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001562 do
1563 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001564 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001565 }
Nate Begeman1486b502009-01-18 01:47:54 +00001566
Mike Stump9afab102009-02-19 03:04:26 +00001567 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001568 // We didn't get to the end of the string. This means the component names
1569 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001570 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1571 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001572 return QualType();
1573 }
Mike Stump9afab102009-02-19 03:04:26 +00001574
Nate Begeman1486b502009-01-18 01:47:54 +00001575 // Ensure no component accessor exceeds the width of the vector type it
1576 // operates on.
1577 if (!HalvingSwizzle) {
1578 compStr = CompName.getName();
1579
1580 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001581 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001582
1583 while (*compStr) {
1584 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1585 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1586 << baseType << SourceRange(CompLoc);
1587 return QualType();
1588 }
1589 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001590 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001591
Nate Begeman1486b502009-01-18 01:47:54 +00001592 // If this is a halving swizzle, verify that the base type has an even
1593 // number of elements.
1594 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001595 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001596 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001597 return QualType();
1598 }
Mike Stump9afab102009-02-19 03:04:26 +00001599
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001600 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001601 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001602 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001603 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001604 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001605 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1606 : CompName.getLength();
1607 if (HexSwizzle)
1608 CompSize--;
1609
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001610 if (CompSize == 1)
1611 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001612
Nate Begemanaf6ed502008-04-18 23:10:10 +00001613 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001614 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001615 // diagostics look bad. We want extended vector types to appear built-in.
1616 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1617 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1618 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001619 }
1620 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001621}
1622
Chris Lattner2cb744b2009-02-15 22:43:40 +00001623
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001624/// constructSetterName - Return the setter name for the given
1625/// identifier, i.e. "set" + Name where the initial character of Name
1626/// has been capitalized.
1627// FIXME: Merge with same routine in Parser. But where should this
1628// live?
1629static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1630 const IdentifierInfo *Name) {
1631 llvm::SmallString<100> SelectorName;
1632 SelectorName = "set";
1633 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1634 SelectorName[3] = toupper(SelectorName[3]);
1635 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1636}
1637
Sebastian Redl8b769972009-01-19 00:08:26 +00001638Action::OwningExprResult
1639Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1640 tok::TokenKind OpKind, SourceLocation MemberLoc,
1641 IdentifierInfo &Member) {
1642 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001643 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001644
1645 // Perform default conversions.
1646 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001647
Steve Naroff2cb66382007-07-26 03:11:44 +00001648 QualType BaseType = BaseExpr->getType();
1649 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001650
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001651 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1652 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001653 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001654 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001655 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001656 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001657 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1658 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001659 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001660 return ExprError(Diag(MemberLoc,
1661 diag::err_typecheck_member_reference_arrow)
1662 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001663 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001664
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001665 // Handle field access to simple records. This also handles access to fields
1666 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001667 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001668 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001669 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001670 diag::err_typecheck_incomplete_tag,
1671 BaseExpr->getSourceRange()))
1672 return ExprError();
1673
Steve Naroff2cb66382007-07-26 03:11:44 +00001674 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001675 // FIXME: Qualified name lookup for C++ is a bit more complicated
1676 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001677 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001678 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001679 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001680
Douglas Gregor09be81b2009-02-04 17:27:36 +00001681 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001682 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001683 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1684 << &Member << BaseExpr->getSourceRange());
1685 else if (Result.isAmbiguous()) {
1686 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1687 MemberLoc, BaseExpr->getSourceRange());
1688 return ExprError();
1689 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001690 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001691
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001692 // If the decl being referenced had an error, return an error for this
1693 // sub-expr without emitting another error, in order to avoid cascading
1694 // error cases.
1695 if (MemberDecl->isInvalidDecl())
1696 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001697
Douglas Gregoraa57e862009-02-18 21:56:37 +00001698 // Check the use of this field
1699 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1700 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001701
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001702 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001703 // We may have found a field within an anonymous union or struct
1704 // (C++ [class.union]).
1705 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001706 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001707 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001708
Douglas Gregor82d44772008-12-20 23:49:58 +00001709 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1710 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001711 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001712 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1713 MemberType = Ref->getPointeeType();
1714 else {
1715 unsigned combinedQualifiers =
1716 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001717 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001718 combinedQualifiers &= ~QualType::Const;
1719 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1720 }
Eli Friedman76b49832008-02-06 22:48:16 +00001721
Steve Naroff774e4152009-01-21 00:14:39 +00001722 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1723 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001724 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001725 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001726 Var, MemberLoc,
1727 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001728 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001729 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001730 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001731 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001732 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001733 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001734 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001735 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001736 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1737 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001738 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001739 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1740 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001741
Douglas Gregor82d44772008-12-20 23:49:58 +00001742 // We found a declaration kind that we didn't expect. This is a
1743 // generic error message that tells the user that she can't refer
1744 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001745 return ExprError(Diag(MemberLoc,
1746 diag::err_typecheck_member_reference_unknown)
1747 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001748 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001749
Chris Lattnere9d71612008-07-21 04:59:05 +00001750 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1751 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001752 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001753 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001754 // If the decl being referenced had an error, return an error for this
1755 // sub-expr without emitting another error, in order to avoid cascading
1756 // error cases.
1757 if (IV->isInvalidDecl())
1758 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001759
1760 // Check whether we can reference this field.
1761 if (DiagnoseUseOfDecl(IV, MemberLoc))
1762 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001763
1764 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001765 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001766 OpKind == tok::arrow);
1767 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001768 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001769 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001770 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1771 << IFTy->getDecl()->getDeclName() << &Member
1772 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001773 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001774
Chris Lattnere9d71612008-07-21 04:59:05 +00001775 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1776 // pointer to a (potentially qualified) interface type.
1777 const PointerType *PTy;
1778 const ObjCInterfaceType *IFTy;
1779 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1780 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1781 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001782
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001783 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001784 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001785 // Check whether we can reference this property.
1786 if (DiagnoseUseOfDecl(PD, MemberLoc))
1787 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001788
Steve Naroff774e4152009-01-21 00:14:39 +00001789 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001790 MemberLoc, BaseExpr));
1791 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001792
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001793 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001794 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1795 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001796 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001797 // Check whether we can reference this property.
1798 if (DiagnoseUseOfDecl(PD, MemberLoc))
1799 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001800
Steve Naroff774e4152009-01-21 00:14:39 +00001801 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001802 MemberLoc, BaseExpr));
1803 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001804
1805 // If that failed, look for an "implicit" property by seeing if the nullary
1806 // selector is implemented.
1807
1808 // FIXME: The logic for looking up nullary and unary selectors should be
1809 // shared with the code in ActOnInstanceMessage.
1810
1811 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1812 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001813
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001814 // If this reference is in an @implementation, check for 'private' methods.
1815 if (!Getter)
1816 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1817 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001818 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001819 ObjCImplementations[ClassDecl->getIdentifier()])
1820 Getter = ImpDecl->getInstanceMethod(Sel);
1821
Steve Naroff04151f32008-10-22 19:16:27 +00001822 // Look through local category implementations associated with the class.
1823 if (!Getter) {
1824 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1825 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1826 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1827 }
1828 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001829 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001830 // Check if we can reference this property.
1831 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1832 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001833
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001834 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001835 // will look for the matching setter, in case it is needed.
1836 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1837 &Member);
1838 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1839 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1840 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001841 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001842 // methods.
1843 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1844 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001845 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001846 ObjCImplementations[ClassDecl->getIdentifier()])
1847 Setter = ImpDecl->getInstanceMethod(SetterSel);
1848 }
1849 // Look through local category implementations associated with the class.
1850 if (!Setter) {
1851 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1852 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1853 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1854 }
1855 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001856
Douglas Gregoraa57e862009-02-18 21:56:37 +00001857 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1858 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001859
Sebastian Redl8b769972009-01-19 00:08:26 +00001860 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001861 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001862 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001863 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001864
1865 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1866 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001867 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001868 // Handle properties on qualified "id" protocols.
1869 const ObjCQualifiedIdType *QIdTy;
1870 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1871 // Check protocols on qualified interfaces.
1872 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001873 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001874 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001875 // Check the use of this declaration
1876 if (DiagnoseUseOfDecl(PD, MemberLoc))
1877 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001878
Steve Naroff774e4152009-01-21 00:14:39 +00001879 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001880 MemberLoc, BaseExpr));
1881 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001882 // Also must look for a getter name which uses property syntax.
1883 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1884 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001885 // Check the use of this method.
1886 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1887 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001888
1889 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001890 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001891 }
1892 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001893
1894 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1895 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001896 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001897 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001898 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001899 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1900 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001901 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001902 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001903 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001904 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001905
1906 return ExprError(Diag(MemberLoc,
1907 diag::err_typecheck_member_reference_struct_union)
1908 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001909}
1910
Douglas Gregor3257fb52008-12-22 05:46:06 +00001911/// ConvertArgumentsForCall - Converts the arguments specified in
1912/// Args/NumArgs to the parameter types of the function FDecl with
1913/// function prototype Proto. Call is the call expression itself, and
1914/// Fn is the function expression. For a C++ member function, this
1915/// routine does not attempt to convert the object argument. Returns
1916/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001917bool
1918Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001919 FunctionDecl *FDecl,
1920 const FunctionTypeProto *Proto,
1921 Expr **Args, unsigned NumArgs,
1922 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001923 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001924 // assignment, to the types of the corresponding parameter, ...
1925 unsigned NumArgsInProto = Proto->getNumArgs();
1926 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001927 bool Invalid = false;
1928
Douglas Gregor3257fb52008-12-22 05:46:06 +00001929 // If too few arguments are available (and we don't have default
1930 // arguments for the remaining parameters), don't make the call.
1931 if (NumArgs < NumArgsInProto) {
1932 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1933 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1934 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1935 // Use default arguments for missing arguments
1936 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001937 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001938 }
1939
1940 // If too many are passed and not variadic, error on the extras and drop
1941 // them.
1942 if (NumArgs > NumArgsInProto) {
1943 if (!Proto->isVariadic()) {
1944 Diag(Args[NumArgsInProto]->getLocStart(),
1945 diag::err_typecheck_call_too_many_args)
1946 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1947 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1948 Args[NumArgs-1]->getLocEnd());
1949 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001950 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001951 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001952 }
1953 NumArgsToCheck = NumArgsInProto;
1954 }
Mike Stump9afab102009-02-19 03:04:26 +00001955
Douglas Gregor3257fb52008-12-22 05:46:06 +00001956 // Continue to check argument types (even if we have too few/many args).
1957 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1958 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001959
Douglas Gregor3257fb52008-12-22 05:46:06 +00001960 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001961 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001962 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001963
1964 // Pass the argument.
1965 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1966 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001967 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001968 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001969 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001970 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00001971
Douglas Gregor3257fb52008-12-22 05:46:06 +00001972 Call->setArg(i, Arg);
1973 }
Mike Stump9afab102009-02-19 03:04:26 +00001974
Douglas Gregor3257fb52008-12-22 05:46:06 +00001975 // If this is a variadic call, handle args passed through "...".
1976 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001977 VariadicCallType CallType = VariadicFunction;
1978 if (Fn->getType()->isBlockPointerType())
1979 CallType = VariadicBlock; // Block
1980 else if (isa<MemberExpr>(Fn))
1981 CallType = VariadicMethod;
1982
Douglas Gregor3257fb52008-12-22 05:46:06 +00001983 // Promote the arguments (C99 6.5.2.2p7).
1984 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1985 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001986 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001987 Call->setArg(i, Arg);
1988 }
1989 }
1990
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001991 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001992}
1993
Steve Naroff87d58b42007-09-16 03:34:24 +00001994/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001995/// This provides the location of the left/right parens and a list of comma
1996/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001997Action::OwningExprResult
1998Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1999 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002000 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002001 unsigned NumArgs = args.size();
2002 Expr *Fn = static_cast<Expr *>(fn.release());
2003 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002004 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002005 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002006 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002007
Douglas Gregor3257fb52008-12-22 05:46:06 +00002008 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002009 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002010 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002011 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2012 bool Dependent = false;
2013 if (Fn->isTypeDependent())
2014 Dependent = true;
2015 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2016 Dependent = true;
2017
2018 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002019 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002020 Context.DependentTy, RParenLoc));
2021
2022 // Determine whether this is a call to an object (C++ [over.call.object]).
2023 if (Fn->getType()->isRecordType())
2024 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2025 CommaLocs, RParenLoc));
2026
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002027 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002028 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2029 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2030 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002031 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2032 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002033 }
2034
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002035 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002036 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002037 Expr *FnExpr = Fn;
2038 bool ADL = true;
2039 while (true) {
2040 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2041 FnExpr = IcExpr->getSubExpr();
2042 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002043 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002044 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002045 ADL = false;
2046 FnExpr = PExpr->getSubExpr();
2047 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002048 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002049 == UnaryOperator::AddrOf) {
2050 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002051 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2052 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2053 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2054 break;
Mike Stump9afab102009-02-19 03:04:26 +00002055 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002056 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2057 UnqualifiedName = DepName->getName();
2058 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002059 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002060 // Any kind of name that does not refer to a declaration (or
2061 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2062 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002063 break;
2064 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002065 }
Mike Stump9afab102009-02-19 03:04:26 +00002066
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002067 OverloadedFunctionDecl *Ovl = 0;
2068 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002069 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002070 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2071 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002072
Douglas Gregorfcb19192009-02-11 23:02:49 +00002073 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002074 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002075 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002076 ADL = false;
2077
Douglas Gregorfcb19192009-02-11 23:02:49 +00002078 // We don't perform ADL in C.
2079 if (!getLangOptions().CPlusPlus)
2080 ADL = false;
2081
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002082 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002083 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2084 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002085 NumArgs, CommaLocs, RParenLoc, ADL);
2086 if (!FDecl)
2087 return ExprError();
2088
2089 // Update Fn to refer to the actual function selected.
2090 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002091 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002092 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002093 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2094 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002095 false, false,
2096 QDRExpr->getSourceRange().getBegin());
2097 else
Mike Stump9afab102009-02-19 03:04:26 +00002098 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002099 Fn->getSourceRange().getBegin());
2100 Fn->Destroy(Context);
2101 Fn = NewFn;
2102 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002103 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002104
2105 // Promote the function operand.
2106 UsualUnaryConversions(Fn);
2107
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002108 // Make the call expr early, before semantic checks. This guarantees cleanup
2109 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002110 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2111 Args, NumArgs,
2112 Context.BoolTy,
2113 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002114
Steve Naroffd6163f32008-09-05 22:11:13 +00002115 const FunctionType *FuncT;
2116 if (!Fn->getType()->isBlockPointerType()) {
2117 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2118 // have type pointer to function".
2119 const PointerType *PT = Fn->getType()->getAsPointerType();
2120 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002121 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2122 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002123 FuncT = PT->getPointeeType()->getAsFunctionType();
2124 } else { // This is a block call.
2125 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2126 getAsFunctionType();
2127 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002128 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002129 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2130 << Fn->getType() << Fn->getSourceRange());
2131
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002132 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002133 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002134
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002135 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002136 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002137 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002138 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002139 } else {
2140 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002141
Steve Naroffdb65e052007-08-28 23:30:39 +00002142 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002143 for (unsigned i = 0; i != NumArgs; i++) {
2144 Expr *Arg = Args[i];
2145 DefaultArgumentPromotion(Arg);
2146 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002147 }
Chris Lattner4b009652007-07-25 00:24:17 +00002148 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002149
Douglas Gregor3257fb52008-12-22 05:46:06 +00002150 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2151 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002152 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2153 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002154
Chris Lattner2e64c072007-08-10 20:18:51 +00002155 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002156 if (FDecl)
2157 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002158
Sebastian Redl8b769972009-01-19 00:08:26 +00002159 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002160}
2161
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002162Action::OwningExprResult
2163Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2164 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002165 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002166 QualType literalType = QualType::getFromOpaquePtr(Ty);
2167 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002168 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002169 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002170
Eli Friedman8c2173d2008-05-20 05:22:08 +00002171 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002172 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002173 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2174 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002175 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2176 diag::err_typecheck_decl_incomplete_type,
2177 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002178 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002179
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002180 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002181 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002182 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002183
Chris Lattnere5cb5862008-12-04 23:50:19 +00002184 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002185 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002186 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002187 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002188 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002189 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002190 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002191 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002192}
2193
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002194Action::OwningExprResult
2195Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2196 InitListDesignations &Designators,
2197 SourceLocation RBraceLoc) {
2198 unsigned NumInit = initlist.size();
2199 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002200
Steve Naroff0acc9c92007-09-15 18:49:24 +00002201 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002202 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002203
Mike Stump9afab102009-02-19 03:04:26 +00002204 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002205 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002206 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002207 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002208}
2209
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002210/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002211bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002212 UsualUnaryConversions(castExpr);
2213
2214 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2215 // type needs to be scalar.
2216 if (castType->isVoidType()) {
2217 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002218 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2219 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002220 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002221 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2222 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2223 (castType->isStructureType() || castType->isUnionType())) {
2224 // GCC struct/union extension: allow cast to self.
2225 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2226 << castType << castExpr->getSourceRange();
2227 } else if (castType->isUnionType()) {
2228 // GCC cast to union extension
2229 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2230 RecordDecl::field_iterator Field, FieldEnd;
2231 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2232 Field != FieldEnd; ++Field) {
2233 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2234 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2235 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2236 << castExpr->getSourceRange();
2237 break;
2238 }
2239 }
2240 if (Field == FieldEnd)
2241 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2242 << castExpr->getType() << castExpr->getSourceRange();
2243 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002244 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002245 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002246 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002247 }
Mike Stump9afab102009-02-19 03:04:26 +00002248 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002249 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002250 return Diag(castExpr->getLocStart(),
2251 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002252 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002253 } else if (castExpr->getType()->isVectorType()) {
2254 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2255 return true;
2256 } else if (castType->isVectorType()) {
2257 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2258 return true;
2259 }
2260 return false;
2261}
2262
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002263bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002264 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002265
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002266 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002267 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002268 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002269 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002270 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002271 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002272 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002273 } else
2274 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002275 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002276 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002277
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002278 return false;
2279}
2280
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002281Action::OwningExprResult
2282Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2283 SourceLocation RParenLoc, ExprArg Op) {
2284 assert((Ty != 0) && (Op.get() != 0) &&
2285 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002286
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002287 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002288 QualType castType = QualType::getFromOpaquePtr(Ty);
2289
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002290 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002291 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002292 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002293 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002294}
2295
Chris Lattner98a425c2007-11-26 01:40:58 +00002296/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2297/// In that case, lex = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002298/// C99 6.5.15
2299QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2300 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002301 UsualUnaryConversions(Cond);
2302 UsualUnaryConversions(LHS);
2303 UsualUnaryConversions(RHS);
2304 QualType CondTy = Cond->getType();
2305 QualType LHSTy = LHS->getType();
2306 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002307
2308 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002309 if (!Cond->isTypeDependent()) {
2310 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2311 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2312 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002313 return QualType();
2314 }
Chris Lattner4b009652007-07-25 00:24:17 +00002315 }
Mike Stump9afab102009-02-19 03:04:26 +00002316
Chris Lattner992ae932008-01-06 22:42:25 +00002317 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002318 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002319 return Context.DependentTy;
2320
Chris Lattner992ae932008-01-06 22:42:25 +00002321 // If both operands have arithmetic type, do the usual arithmetic conversions
2322 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002323 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2324 UsualArithmeticConversions(LHS, RHS);
2325 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002326 }
Mike Stump9afab102009-02-19 03:04:26 +00002327
Chris Lattner992ae932008-01-06 22:42:25 +00002328 // If both operands are the same structure or union type, the result is that
2329 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002330 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2331 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002332 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002333 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002334 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002335 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002336 }
Mike Stump9afab102009-02-19 03:04:26 +00002337
Chris Lattner992ae932008-01-06 22:42:25 +00002338 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002339 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002340 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2341 if (!LHSTy->isVoidType())
2342 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2343 << RHS->getSourceRange();
2344 if (!RHSTy->isVoidType())
2345 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2346 << LHS->getSourceRange();
2347 ImpCastExprToType(LHS, Context.VoidTy);
2348 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002349 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002350 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002351 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2352 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002353 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2354 Context.isObjCObjectPointerType(LHSTy)) &&
2355 RHS->isNullPointerConstant(Context)) {
2356 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2357 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002358 }
Chris Lattnere2897262009-02-18 04:28:32 +00002359 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2360 Context.isObjCObjectPointerType(RHSTy)) &&
2361 LHS->isNullPointerConstant(Context)) {
2362 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2363 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002364 }
Mike Stump9afab102009-02-19 03:04:26 +00002365
Chris Lattner0ac51632008-01-06 22:50:31 +00002366 // Handle the case where both operands are pointers before we handle null
2367 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002368 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2369 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002370 // get the "pointed to" types
2371 QualType lhptee = LHSPT->getPointeeType();
2372 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002373
Chris Lattner71225142007-07-31 21:27:01 +00002374 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2375 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002376 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002377 // Figure out necessary qualifiers (C99 6.5.15p6)
2378 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002379 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002380 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2381 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002382 return destType;
2383 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002384 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002385 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002386 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002387 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2388 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002389 return destType;
2390 }
Chris Lattner4b009652007-07-25 00:24:17 +00002391
Chris Lattner9c039b52009-02-18 04:38:20 +00002392 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002393 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002394 return LHSTy;
2395 }
Mike Stump9afab102009-02-19 03:04:26 +00002396
Chris Lattnere2897262009-02-18 04:28:32 +00002397 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002398
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002399 // If either type is an Objective-C object type then check
2400 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002401 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002402 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002403 // If both operands are interfaces and either operand can be
2404 // assigned to the other, use that type as the composite
2405 // type. This allows
2406 // xxx ? (A*) a : (B*) b
2407 // where B is a subclass of A.
2408 //
2409 // Additionally, as for assignment, if either type is 'id'
2410 // allow silent coercion. Finally, if the types are
2411 // incompatible then make sure to use 'id' as the composite
2412 // type so the result is acceptable for sending messages to.
2413
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002414 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002415 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002416 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2417 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2418 if (LHSIface && RHSIface &&
2419 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002420 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002421 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002422 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002423 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002424 } else if (Context.isObjCIdStructType(lhptee) ||
2425 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002426 compositeType = Context.getObjCIdType();
2427 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002428 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002429 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002430 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002431 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002432 ImpCastExprToType(LHS, incompatTy);
2433 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002434 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002435 }
Mike Stump9afab102009-02-19 03:04:26 +00002436 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002437 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002438 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2439 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002440 // In this situation, we assume void* type. No especially good
2441 // reason, but this is what gcc does, and we do have to pick
2442 // to get a consistent AST.
2443 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002444 ImpCastExprToType(LHS, incompatTy);
2445 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002446 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002447 }
2448 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002449 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2450 // differently qualified versions of compatible types, the result type is
2451 // a pointer to an appropriately qualified version of the *composite*
2452 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002453 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002454 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002455 ImpCastExprToType(LHS, compositeType);
2456 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002457 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002458 }
Chris Lattner4b009652007-07-25 00:24:17 +00002459 }
Mike Stump9afab102009-02-19 03:04:26 +00002460
Chris Lattner9c039b52009-02-18 04:38:20 +00002461 // Selection between block pointer types is ok as long as they are the same.
2462 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2463 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2464 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002465
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002466 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2467 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002468 // id with statically typed objects).
2469 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002470 // GCC allows qualified id and any Objective-C type to devolve to
2471 // id. Currently localizing to here until clear this should be
2472 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002473 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002474 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002475 Context.isObjCObjectPointerType(RHSTy)) ||
2476 (RHSTy->isObjCQualifiedIdType() &&
2477 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002478 // FIXME: This is not the correct composite type. This only
2479 // happens to work because id can more or less be used anywhere,
2480 // however this may change the type of method sends.
2481 // FIXME: gcc adds some type-checking of the arguments and emits
2482 // (confusing) incompatible comparison warnings in some
2483 // cases. Investigate.
2484 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002485 ImpCastExprToType(LHS, compositeType);
2486 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002487 return compositeType;
2488 }
2489 }
2490
Chris Lattner992ae932008-01-06 22:42:25 +00002491 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002492 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2493 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002494 return QualType();
2495}
2496
Steve Naroff87d58b42007-09-16 03:34:24 +00002497/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002498/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002499Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2500 SourceLocation ColonLoc,
2501 ExprArg Cond, ExprArg LHS,
2502 ExprArg RHS) {
2503 Expr *CondExpr = (Expr *) Cond.get();
2504 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002505
2506 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2507 // was the condition.
2508 bool isLHSNull = LHSExpr == 0;
2509 if (isLHSNull)
2510 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002511
2512 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002513 RHSExpr, QuestionLoc);
2514 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002515 return ExprError();
2516
2517 Cond.release();
2518 LHS.release();
2519 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002520 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002521 isLHSNull ? 0 : LHSExpr,
2522 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002523}
2524
Chris Lattner4b009652007-07-25 00:24:17 +00002525
2526// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002527// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002528// routine is it effectively iqnores the qualifiers on the top level pointee.
2529// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2530// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002531Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002532Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2533 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002534
Chris Lattner4b009652007-07-25 00:24:17 +00002535 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002536 lhptee = lhsType->getAsPointerType()->getPointeeType();
2537 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002538
Chris Lattner4b009652007-07-25 00:24:17 +00002539 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002540 lhptee = Context.getCanonicalType(lhptee);
2541 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002542
Chris Lattner005ed752008-01-04 18:04:52 +00002543 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002544
2545 // C99 6.5.16.1p1: This following citation is common to constraints
2546 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2547 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002548 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002549 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002550 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002551
Mike Stump9afab102009-02-19 03:04:26 +00002552 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2553 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002554 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002555 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002556 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002557 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002558
Chris Lattner4ca3d772008-01-03 22:56:36 +00002559 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002560 assert(rhptee->isFunctionType());
2561 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002562 }
Mike Stump9afab102009-02-19 03:04:26 +00002563
Chris Lattner4ca3d772008-01-03 22:56:36 +00002564 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002565 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002566 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002567
2568 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002569 assert(lhptee->isFunctionType());
2570 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002571 }
Mike Stump9afab102009-02-19 03:04:26 +00002572 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002573 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002574 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002575 rhptee.getUnqualifiedType()))
2576 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002577 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002578}
2579
Steve Naroff3454b6c2008-09-04 15:10:53 +00002580/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2581/// block pointer types are compatible or whether a block and normal pointer
2582/// are compatible. It is more restrict than comparing two function pointer
2583// types.
Mike Stump9afab102009-02-19 03:04:26 +00002584Sema::AssignConvertType
2585Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002586 QualType rhsType) {
2587 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002588
Steve Naroff3454b6c2008-09-04 15:10:53 +00002589 // get the "pointed to" type (ignoring qualifiers at the top level)
2590 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002591 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2592
Steve Naroff3454b6c2008-09-04 15:10:53 +00002593 // make sure we operate on the canonical type
2594 lhptee = Context.getCanonicalType(lhptee);
2595 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002596
Steve Naroff3454b6c2008-09-04 15:10:53 +00002597 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002598
Steve Naroff3454b6c2008-09-04 15:10:53 +00002599 // For blocks we enforce that qualifiers are identical.
2600 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2601 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002602
Steve Naroff3454b6c2008-09-04 15:10:53 +00002603 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002604 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002605 return ConvTy;
2606}
2607
Mike Stump9afab102009-02-19 03:04:26 +00002608/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2609/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002610/// pointers. Here are some objectionable examples that GCC considers warnings:
2611///
2612/// int a, *pint;
2613/// short *pshort;
2614/// struct foo *pfoo;
2615///
2616/// pint = pshort; // warning: assignment from incompatible pointer type
2617/// a = pint; // warning: assignment makes integer from pointer without a cast
2618/// pint = a; // warning: assignment makes pointer from integer without a cast
2619/// pint = pfoo; // warning: assignment from incompatible pointer type
2620///
2621/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002622/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002623///
Chris Lattner005ed752008-01-04 18:04:52 +00002624Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002625Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002626 // Get canonical types. We're not formatting these types, just comparing
2627 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002628 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2629 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002630
2631 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002632 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002633
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002634 // If the left-hand side is a reference type, then we are in a
2635 // (rare!) case where we've allowed the use of references in C,
2636 // e.g., as a parameter type in a built-in function. In this case,
2637 // just make sure that the type referenced is compatible with the
2638 // right-hand side type. The caller is responsible for adjusting
2639 // lhsType so that the resulting expression does not have reference
2640 // type.
2641 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2642 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002643 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002644 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002645 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002646
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002647 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2648 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002649 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002650 // Relax integer conversions like we do for pointers below.
2651 if (rhsType->isIntegerType())
2652 return IntToPointer;
2653 if (lhsType->isIntegerType())
2654 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002655 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002656 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002657
Nate Begemanc5f0f652008-07-14 18:02:46 +00002658 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002659 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002660 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2661 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002662 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002663
Nate Begemanc5f0f652008-07-14 18:02:46 +00002664 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002665 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002666 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002667 if (getLangOptions().LaxVectorConversions &&
2668 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002669 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002670 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002671 }
2672 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002673 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002674
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002675 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002676 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002677
Chris Lattner390564e2008-04-07 06:49:41 +00002678 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002679 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002680 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002681
Chris Lattner390564e2008-04-07 06:49:41 +00002682 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002683 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002684
Steve Naroffa982c712008-09-29 18:10:17 +00002685 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002686 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002687 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002688
2689 // Treat block pointers as objects.
2690 if (getLangOptions().ObjC1 &&
2691 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2692 return Compatible;
2693 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002694 return Incompatible;
2695 }
2696
2697 if (isa<BlockPointerType>(lhsType)) {
2698 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002699 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002700
Steve Naroffa982c712008-09-29 18:10:17 +00002701 // Treat block pointers as objects.
2702 if (getLangOptions().ObjC1 &&
2703 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2704 return Compatible;
2705
Steve Naroff3454b6c2008-09-04 15:10:53 +00002706 if (rhsType->isBlockPointerType())
2707 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002708
Steve Naroff3454b6c2008-09-04 15:10:53 +00002709 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2710 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002711 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002712 }
Chris Lattner1853da22008-01-04 23:18:45 +00002713 return Incompatible;
2714 }
2715
Chris Lattner390564e2008-04-07 06:49:41 +00002716 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002717 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002718 if (lhsType == Context.BoolTy)
2719 return Compatible;
2720
2721 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002722 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002723
Mike Stump9afab102009-02-19 03:04:26 +00002724 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002725 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002726
2727 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002728 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002729 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002730 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002731 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002732
Chris Lattner1853da22008-01-04 23:18:45 +00002733 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002734 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002735 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002736 }
2737 return Incompatible;
2738}
2739
Chris Lattner005ed752008-01-04 18:04:52 +00002740Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002741Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002742 if (getLangOptions().CPlusPlus) {
2743 if (!lhsType->isRecordType()) {
2744 // C++ 5.17p3: If the left operand is not of class type, the
2745 // expression is implicitly converted (C++ 4) to the
2746 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002747 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2748 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002749 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002750 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002751 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002752 }
2753
2754 // FIXME: Currently, we fall through and treat C++ classes like C
2755 // structures.
2756 }
2757
Steve Naroffcdee22d2007-11-27 17:58:44 +00002758 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2759 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002760 if ((lhsType->isPointerType() ||
2761 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002762 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002763 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002764 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002765 return Compatible;
2766 }
Mike Stump9afab102009-02-19 03:04:26 +00002767
Chris Lattner5f505bf2007-10-16 02:55:40 +00002768 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002769 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002770 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002771 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002772 //
Mike Stump9afab102009-02-19 03:04:26 +00002773 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002774 if (!lhsType->isReferenceType())
2775 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002776
Chris Lattner005ed752008-01-04 18:04:52 +00002777 Sema::AssignConvertType result =
2778 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002779
Steve Naroff0f32f432007-08-24 22:33:52 +00002780 // C99 6.5.16.1p2: The value of the right operand is converted to the
2781 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002782 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2783 // so that we can use references in built-in functions even in C.
2784 // The getNonReferenceType() call makes sure that the resulting expression
2785 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002786 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002787 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002788 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002789}
2790
Chris Lattner005ed752008-01-04 18:04:52 +00002791Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002792Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2793 return CheckAssignmentConstraints(lhsType, rhsType);
2794}
2795
Chris Lattner1eafdea2008-11-18 01:30:42 +00002796QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002797 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002798 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002799 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002800 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002801}
2802
Mike Stump9afab102009-02-19 03:04:26 +00002803inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002804 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002805 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002806 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002807 QualType lhsType =
2808 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2809 QualType rhsType =
2810 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002811
Nate Begemanc5f0f652008-07-14 18:02:46 +00002812 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002813 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002814 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002815
Nate Begemanc5f0f652008-07-14 18:02:46 +00002816 // Handle the case of a vector & extvector type of the same size and element
2817 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002818 if (getLangOptions().LaxVectorConversions) {
2819 // FIXME: Should we warn here?
2820 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002821 if (const VectorType *RV = rhsType->getAsVectorType())
2822 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002823 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002824 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002825 }
2826 }
2827 }
Mike Stump9afab102009-02-19 03:04:26 +00002828
Nate Begemanc5f0f652008-07-14 18:02:46 +00002829 // If the lhs is an extended vector and the rhs is a scalar of the same type
2830 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002831 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002832 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002833
2834 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002835 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2836 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002837 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002838 return lhsType;
2839 }
2840 }
2841
Nate Begemanc5f0f652008-07-14 18:02:46 +00002842 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002843 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002844 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002845 QualType eltType = V->getElementType();
2846
Mike Stump9afab102009-02-19 03:04:26 +00002847 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002848 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2849 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002850 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002851 return rhsType;
2852 }
2853 }
2854
Chris Lattner4b009652007-07-25 00:24:17 +00002855 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002856 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002857 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002858 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002859 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002860}
2861
Chris Lattner4b009652007-07-25 00:24:17 +00002862inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002863 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002864{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002865 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002866 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002867
Steve Naroff8f708362007-08-24 19:07:16 +00002868 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002869
Chris Lattner4b009652007-07-25 00:24:17 +00002870 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002871 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002872 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002873}
2874
2875inline QualType Sema::CheckRemainderOperands(
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 Dunbarb27282f2009-01-05 22:55:36 +00002878 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2879 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2880 return CheckVectorOperands(Loc, lex, rex);
2881 return InvalidOperands(Loc, lex, rex);
2882 }
Chris Lattner4b009652007-07-25 00:24:17 +00002883
Steve Naroff8f708362007-08-24 19:07:16 +00002884 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002885
Chris Lattner4b009652007-07-25 00:24:17 +00002886 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002887 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002888 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002889}
2890
2891inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002892 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002893{
2894 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002895 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002896
Steve Naroff8f708362007-08-24 19:07:16 +00002897 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002898
Chris Lattner4b009652007-07-25 00:24:17 +00002899 // handle the common case first (both operands are arithmetic).
2900 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002901 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002902
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002903 // Put any potential pointer into PExp
2904 Expr* PExp = lex, *IExp = rex;
2905 if (IExp->getType()->isPointerType())
2906 std::swap(PExp, IExp);
2907
2908 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2909 if (IExp->getType()->isIntegerType()) {
2910 // Check for arithmetic on pointers to incomplete types
2911 if (!PTy->getPointeeType()->isObjectType()) {
2912 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002913 if (getLangOptions().CPlusPlus) {
2914 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2915 << lex->getSourceRange() << rex->getSourceRange();
2916 return QualType();
2917 }
2918
2919 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002920 Diag(Loc, diag::ext_gnu_void_ptr)
2921 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002922 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002923 if (getLangOptions().CPlusPlus) {
2924 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2925 << lex->getType() << lex->getSourceRange();
2926 return QualType();
2927 }
2928
2929 // GNU extension: arithmetic on pointer to function
2930 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002931 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002932 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002933 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002934 diag::err_typecheck_arithmetic_incomplete_type,
2935 lex->getSourceRange(), SourceRange(),
2936 lex->getType());
2937 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002938 }
2939 }
2940 return PExp->getType();
2941 }
2942 }
2943
Chris Lattner1eafdea2008-11-18 01:30:42 +00002944 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002945}
2946
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002947// C99 6.5.6
2948QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002949 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002950 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002951 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002952
Steve Naroff8f708362007-08-24 19:07:16 +00002953 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002954
Chris Lattnerf6da2912007-12-09 21:53:25 +00002955 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002956
Chris Lattnerf6da2912007-12-09 21:53:25 +00002957 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002958 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002959 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002960
Chris Lattnerf6da2912007-12-09 21:53:25 +00002961 // Either ptr - int or ptr - ptr.
2962 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002963 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002964
Chris Lattnerf6da2912007-12-09 21:53:25 +00002965 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002966 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002967 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002968 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002969 Diag(Loc, diag::ext_gnu_void_ptr)
2970 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002971 } else if (lpointee->isFunctionType()) {
2972 if (getLangOptions().CPlusPlus) {
2973 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2974 << lex->getType() << lex->getSourceRange();
2975 return QualType();
2976 }
2977
2978 // GNU extension: arithmetic on pointer to function
2979 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2980 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002981 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002982 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002983 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002984 return QualType();
2985 }
2986 }
2987
2988 // The result type of a pointer-int computation is the pointer type.
2989 if (rex->getType()->isIntegerType())
2990 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002991
Chris Lattnerf6da2912007-12-09 21:53:25 +00002992 // Handle pointer-pointer subtractions.
2993 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002994 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002995
Chris Lattnerf6da2912007-12-09 21:53:25 +00002996 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002997 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002998 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002999 if (rpointee->isVoidType()) {
3000 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003001 Diag(Loc, diag::ext_gnu_void_ptr)
3002 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003003 } else if (rpointee->isFunctionType()) {
3004 if (getLangOptions().CPlusPlus) {
3005 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3006 << rex->getType() << rex->getSourceRange();
3007 return QualType();
3008 }
Mike Stump9afab102009-02-19 03:04:26 +00003009
Douglas Gregorf93eda12009-01-23 19:03:35 +00003010 // GNU extension: arithmetic on pointer to function
3011 if (!lpointee->isFunctionType())
3012 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3013 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003014 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003015 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003016 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003017 return QualType();
3018 }
3019 }
Mike Stump9afab102009-02-19 03:04:26 +00003020
Chris Lattnerf6da2912007-12-09 21:53:25 +00003021 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003022 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003023 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003024 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003025 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003026 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003027 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003028 return QualType();
3029 }
Mike Stump9afab102009-02-19 03:04:26 +00003030
Chris Lattnerf6da2912007-12-09 21:53:25 +00003031 return Context.getPointerDiffType();
3032 }
3033 }
Mike Stump9afab102009-02-19 03:04:26 +00003034
Chris Lattner1eafdea2008-11-18 01:30:42 +00003035 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003036}
3037
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003038// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003039QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003040 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003041 // C99 6.5.7p2: Each of the operands shall have integer type.
3042 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003043 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003044
Chris Lattner2c8bff72007-12-12 05:47:28 +00003045 // Shifts don't perform usual arithmetic conversions, they just do integer
3046 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003047 if (!isCompAssign)
3048 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003049 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003050
Chris Lattner2c8bff72007-12-12 05:47:28 +00003051 // "The type of the result is that of the promoted left operand."
3052 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003053}
3054
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003055// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003056QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003057 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003058 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003059 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003060
Chris Lattner254f3bc2007-08-26 01:18:55 +00003061 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003062 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3063 UsualArithmeticConversions(lex, rex);
3064 else {
3065 UsualUnaryConversions(lex);
3066 UsualUnaryConversions(rex);
3067 }
Chris Lattner4b009652007-07-25 00:24:17 +00003068 QualType lType = lex->getType();
3069 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003070
Ted Kremenek486509e2007-10-29 17:13:39 +00003071 // For non-floating point types, check for self-comparisons of the form
3072 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3073 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003074 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003075 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3076 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003077 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003078 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003079 }
Mike Stump9afab102009-02-19 03:04:26 +00003080
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003081 // The result of comparisons is 'bool' in C++, 'int' in C.
3082 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3083
Chris Lattner254f3bc2007-08-26 01:18:55 +00003084 if (isRelational) {
3085 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003086 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003087 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003088 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003089 if (lType->isFloatingType()) {
3090 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003091 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003092 }
Mike Stump9afab102009-02-19 03:04:26 +00003093
Chris Lattner254f3bc2007-08-26 01:18:55 +00003094 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003095 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003096 }
Mike Stump9afab102009-02-19 03:04:26 +00003097
Chris Lattner22be8422007-08-26 01:10:14 +00003098 bool LHSIsNull = lex->isNullPointerConstant(Context);
3099 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003100
Chris Lattner254f3bc2007-08-26 01:18:55 +00003101 // All of the following pointer related warnings are GCC extensions, except
3102 // when handling null pointer constants. One day, we can consider making them
3103 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003104 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003105 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003106 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003107 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003108 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003109
Steve Naroff3b435622007-11-13 14:57:38 +00003110 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003111 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3112 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003113 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003114 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003115 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003116 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003117 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003118 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003119 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003120 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003121 // Handle block pointer types.
3122 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3123 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3124 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003125
Steve Naroff3454b6c2008-09-04 15:10:53 +00003126 if (!LHSIsNull && !RHSIsNull &&
3127 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003128 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003129 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003130 }
3131 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003132 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003133 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003134 // Allow block pointers to be compared with null pointer constants.
3135 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3136 (lType->isPointerType() && rType->isBlockPointerType())) {
3137 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003138 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003139 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003140 }
3141 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003142 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003143 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003144
Steve Naroff936c4362008-06-03 14:04:54 +00003145 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003146 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003147 const PointerType *LPT = lType->getAsPointerType();
3148 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003149 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003150 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003151 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003152 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003153
Steve Naroff030fcda2008-11-17 19:49:16 +00003154 if (!LPtrToVoid && !RPtrToVoid &&
3155 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003156 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003157 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003158 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003159 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003160 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003161 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003162 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003163 }
Steve Naroff936c4362008-06-03 14:04:54 +00003164 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3165 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003166 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003167 } else {
3168 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003169 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003170 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003171 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003172 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003173 }
Steve Naroff936c4362008-06-03 14:04:54 +00003174 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003175 }
Mike Stump9afab102009-02-19 03:04:26 +00003176 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003177 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003178 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003179 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003180 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003181 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003182 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003183 }
Mike Stump9afab102009-02-19 03:04:26 +00003184 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003185 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003186 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003187 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003188 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003189 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003190 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003191 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003192 // Handle block pointers.
3193 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3194 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003195 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003196 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003197 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003198 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003199 }
3200 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3201 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003202 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003203 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003204 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003205 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003206 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003207 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003208}
3209
Nate Begemanc5f0f652008-07-14 18:02:46 +00003210/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003211/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003212/// like a scalar comparison, a vector comparison produces a vector of integer
3213/// types.
3214QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003215 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003216 bool isRelational) {
3217 // Check to make sure we're operating on vectors of the same type and width,
3218 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003219 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003220 if (vType.isNull())
3221 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003222
Nate Begemanc5f0f652008-07-14 18:02:46 +00003223 QualType lType = lex->getType();
3224 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003225
Nate Begemanc5f0f652008-07-14 18:02:46 +00003226 // For non-floating point types, check for self-comparisons of the form
3227 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3228 // often indicate logic errors in the program.
3229 if (!lType->isFloatingType()) {
3230 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3231 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3232 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003233 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003234 }
Mike Stump9afab102009-02-19 03:04:26 +00003235
Nate Begemanc5f0f652008-07-14 18:02:46 +00003236 // Check for comparisons of floating point operands using != and ==.
3237 if (!isRelational && lType->isFloatingType()) {
3238 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003239 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003240 }
Mike Stump9afab102009-02-19 03:04:26 +00003241
Nate Begemanc5f0f652008-07-14 18:02:46 +00003242 // Return the type for the comparison, which is the same as vector type for
3243 // integer vectors, or an integer type of identical size and number of
3244 // elements for floating point vectors.
3245 if (lType->isIntegerType())
3246 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003247
Nate Begemanc5f0f652008-07-14 18:02:46 +00003248 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003249 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003250 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003251 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003252 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3253 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3254
Mike Stump9afab102009-02-19 03:04:26 +00003255 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003256 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003257 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3258}
3259
Chris Lattner4b009652007-07-25 00:24:17 +00003260inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003261 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003262{
3263 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003264 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003265
Steve Naroff8f708362007-08-24 19:07:16 +00003266 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003267
Chris Lattner4b009652007-07-25 00:24:17 +00003268 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003269 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003270 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003271}
3272
3273inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003274 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003275{
3276 UsualUnaryConversions(lex);
3277 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003278
Eli Friedmanbea3f842008-05-13 20:16:47 +00003279 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003280 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003281 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003282}
3283
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003284/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3285/// is a read-only property; return true if so. A readonly property expression
3286/// depends on various declarations and thus must be treated specially.
3287///
Mike Stump9afab102009-02-19 03:04:26 +00003288static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003289{
3290 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3291 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3292 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3293 QualType BaseType = PropExpr->getBase()->getType();
3294 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003295 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003296 PTy->getPointeeType()->getAsObjCInterfaceType())
3297 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3298 if (S.isPropertyReadonly(PDecl, IFace))
3299 return true;
3300 }
3301 }
3302 return false;
3303}
3304
Chris Lattner4c2642c2008-11-18 01:22:49 +00003305/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3306/// emit an error and return true. If so, return false.
3307static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003308 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3309 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3310 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003311 if (IsLV == Expr::MLV_Valid)
3312 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003313
Chris Lattner4c2642c2008-11-18 01:22:49 +00003314 unsigned Diag = 0;
3315 bool NeedType = false;
3316 switch (IsLV) { // C99 6.5.16p2
3317 default: assert(0 && "Unknown result from isModifiableLvalue!");
3318 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003319 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003320 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3321 NeedType = true;
3322 break;
Mike Stump9afab102009-02-19 03:04:26 +00003323 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003324 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3325 NeedType = true;
3326 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003327 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003328 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3329 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003330 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003331 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3332 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003333 case Expr::MLV_IncompleteType:
3334 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003335 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003336 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3337 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003338 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003339 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3340 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003341 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003342 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3343 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003344 case Expr::MLV_ReadonlyProperty:
3345 Diag = diag::error_readonly_property_assignment;
3346 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003347 case Expr::MLV_NoSetterProperty:
3348 Diag = diag::error_nosetter_property_assignment;
3349 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003350 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003351
Chris Lattner4c2642c2008-11-18 01:22:49 +00003352 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003353 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003354 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003355 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003356 return true;
3357}
3358
3359
3360
3361// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003362QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3363 SourceLocation Loc,
3364 QualType CompoundType) {
3365 // Verify that LHS is a modifiable lvalue, and emit error if not.
3366 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003367 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003368
3369 QualType LHSType = LHS->getType();
3370 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003371
Chris Lattner005ed752008-01-04 18:04:52 +00003372 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003373 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003374 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003375 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003376 // Special case of NSObject attributes on c-style pointer types.
3377 if (ConvTy == IncompatiblePointer &&
3378 ((Context.isObjCNSObjectType(LHSType) &&
3379 Context.isObjCObjectPointerType(RHSType)) ||
3380 (Context.isObjCNSObjectType(RHSType) &&
3381 Context.isObjCObjectPointerType(LHSType))))
3382 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003383
Chris Lattner34c85082008-08-21 18:04:13 +00003384 // If the RHS is a unary plus or minus, check to see if they = and + are
3385 // right next to each other. If so, the user may have typo'd "x =+ 4"
3386 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003387 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003388 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3389 RHSCheck = ICE->getSubExpr();
3390 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3391 if ((UO->getOpcode() == UnaryOperator::Plus ||
3392 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003393 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003394 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003395 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003396 Diag(Loc, diag::warn_not_compound_assign)
3397 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3398 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003399 }
3400 } else {
3401 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003402 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003403 }
Chris Lattner005ed752008-01-04 18:04:52 +00003404
Chris Lattner1eafdea2008-11-18 01:30:42 +00003405 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3406 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003407 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003408
Chris Lattner4b009652007-07-25 00:24:17 +00003409 // C99 6.5.16p3: The type of an assignment expression is the type of the
3410 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003411 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003412 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3413 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003414 // C++ 5.17p1: the type of the assignment expression is that of its left
3415 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003416 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003417}
3418
Chris Lattner1eafdea2008-11-18 01:30:42 +00003419// C99 6.5.17
3420QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3421 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003422
Chris Lattner03c430f2008-07-25 20:54:07 +00003423 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003424 DefaultFunctionArrayConversion(RHS);
3425 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003426}
3427
3428/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3429/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003430QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3431 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003432 QualType ResType = Op->getType();
3433 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003434
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003435 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3436 // Decrement of bool is not allowed.
3437 if (!isInc) {
3438 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3439 return QualType();
3440 }
3441 // Increment of bool sets it to true, but is deprecated.
3442 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3443 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003444 // OK!
3445 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3446 // C99 6.5.2.4p2, 6.5.6p2
3447 if (PT->getPointeeType()->isObjectType()) {
3448 // Pointer to object is ok!
3449 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003450 if (getLangOptions().CPlusPlus) {
3451 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3452 << Op->getSourceRange();
3453 return QualType();
3454 }
3455
3456 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003457 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003458 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003459 if (getLangOptions().CPlusPlus) {
3460 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3461 << Op->getType() << Op->getSourceRange();
3462 return QualType();
3463 }
3464
3465 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003466 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003467 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003468 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003469 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003470 diag::err_typecheck_arithmetic_incomplete_type,
3471 Op->getSourceRange(), SourceRange(),
3472 ResType);
3473 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003474 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003475 } else if (ResType->isComplexType()) {
3476 // C99 does not support ++/-- on complex types, we allow as an extension.
3477 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003478 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003479 } else {
3480 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003481 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003482 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003483 }
Mike Stump9afab102009-02-19 03:04:26 +00003484 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003485 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003486 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003487 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003488 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003489}
3490
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003491/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003492/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003493/// where the declaration is needed for type checking. We only need to
3494/// handle cases when the expression references a function designator
3495/// or is an lvalue. Here are some examples:
3496/// - &(x) => x
3497/// - &*****f => f for f a function designator.
3498/// - &s.xx => s
3499/// - &s.zz[1].yy -> s, if zz is an array
3500/// - *(x + 1) -> x, if x is an array
3501/// - &"123"[2] -> 0
3502/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003503static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003504 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003505 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003506 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003507 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003508 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003509 // Fields cannot be declared with a 'register' storage class.
3510 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003511 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003512 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003513 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003514 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003515 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003516
Douglas Gregord2baafd2008-10-21 16:13:35 +00003517 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003518 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003519 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003520 return 0;
3521 else
3522 return VD;
3523 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003524 case Stmt::UnaryOperatorClass: {
3525 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003526
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003527 switch(UO->getOpcode()) {
3528 case UnaryOperator::Deref: {
3529 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003530 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3531 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3532 if (!VD || VD->getType()->isPointerType())
3533 return 0;
3534 return VD;
3535 }
3536 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003537 }
3538 case UnaryOperator::Real:
3539 case UnaryOperator::Imag:
3540 case UnaryOperator::Extension:
3541 return getPrimaryDecl(UO->getSubExpr());
3542 default:
3543 return 0;
3544 }
3545 }
3546 case Stmt::BinaryOperatorClass: {
3547 BinaryOperator *BO = cast<BinaryOperator>(E);
3548
3549 // Handle cases involving pointer arithmetic. The result of an
3550 // Assign or AddAssign is not an lvalue so they can be ignored.
3551
3552 // (x + n) or (n + x) => x
3553 if (BO->getOpcode() == BinaryOperator::Add) {
3554 if (BO->getLHS()->getType()->isPointerType()) {
3555 return getPrimaryDecl(BO->getLHS());
3556 } else if (BO->getRHS()->getType()->isPointerType()) {
3557 return getPrimaryDecl(BO->getRHS());
3558 }
3559 }
3560
3561 return 0;
3562 }
Chris Lattner4b009652007-07-25 00:24:17 +00003563 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003564 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003565 case Stmt::ImplicitCastExprClass:
3566 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003567 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003568 default:
3569 return 0;
3570 }
3571}
3572
3573/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003574/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003575/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003576/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003577/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003578/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003579/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003580QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003581 if (op->isTypeDependent())
3582 return Context.DependentTy;
3583
Steve Naroff9c6c3592008-01-13 17:10:08 +00003584 if (getLangOptions().C99) {
3585 // Implement C99-only parts of addressof rules.
3586 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3587 if (uOp->getOpcode() == UnaryOperator::Deref)
3588 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3589 // (assuming the deref expression is valid).
3590 return uOp->getSubExpr()->getType();
3591 }
3592 // Technically, there should be a check for array subscript
3593 // expressions here, but the result of one is always an lvalue anyway.
3594 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003595 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003596 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003597
Chris Lattner4b009652007-07-25 00:24:17 +00003598 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003599 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3600 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003601 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3602 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003603 return QualType();
3604 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003605 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003606 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3607 if (Field->isBitField()) {
3608 Diag(OpLoc, diag::err_typecheck_address_of)
3609 << "bit-field" << op->getSourceRange();
3610 return QualType();
3611 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003612 }
3613 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003614 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3615 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003616 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003617 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003618 return QualType();
3619 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003620 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003621 // with the register storage-class specifier.
3622 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3623 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003624 Diag(OpLoc, diag::err_typecheck_address_of)
3625 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003626 return QualType();
3627 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003628 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003629 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003630 } else if (isa<FieldDecl>(dcl)) {
3631 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003632 // Could be a pointer to member, though, if there is an explicit
3633 // scope qualifier for the class.
3634 if (isa<QualifiedDeclRefExpr>(op)) {
3635 DeclContext *Ctx = dcl->getDeclContext();
3636 if (Ctx && Ctx->isRecord())
3637 return Context.getMemberPointerType(op->getType(),
3638 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3639 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003640 } else if (isa<FunctionDecl>(dcl)) {
3641 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003642 // As above.
3643 if (isa<QualifiedDeclRefExpr>(op)) {
3644 DeclContext *Ctx = dcl->getDeclContext();
3645 if (Ctx && Ctx->isRecord())
3646 return Context.getMemberPointerType(op->getType(),
3647 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3648 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003649 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003650 else
Chris Lattner4b009652007-07-25 00:24:17 +00003651 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003652 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003653
Chris Lattner4b009652007-07-25 00:24:17 +00003654 // If the operand has type "type", the result has type "pointer to type".
3655 return Context.getPointerType(op->getType());
3656}
3657
Chris Lattnerda5c0872008-11-23 09:13:29 +00003658QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3659 UsualUnaryConversions(Op);
3660 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003661
Chris Lattnerda5c0872008-11-23 09:13:29 +00003662 // Note that per both C89 and C99, this is always legal, even if ptype is an
3663 // incomplete type or void. It would be possible to warn about dereferencing
3664 // a void pointer, but it's completely well-defined, and such a warning is
3665 // unlikely to catch any mistakes.
3666 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003667 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003668
Chris Lattner77d52da2008-11-20 06:06:08 +00003669 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003670 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003671 return QualType();
3672}
3673
3674static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3675 tok::TokenKind Kind) {
3676 BinaryOperator::Opcode Opc;
3677 switch (Kind) {
3678 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003679 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3680 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003681 case tok::star: Opc = BinaryOperator::Mul; break;
3682 case tok::slash: Opc = BinaryOperator::Div; break;
3683 case tok::percent: Opc = BinaryOperator::Rem; break;
3684 case tok::plus: Opc = BinaryOperator::Add; break;
3685 case tok::minus: Opc = BinaryOperator::Sub; break;
3686 case tok::lessless: Opc = BinaryOperator::Shl; break;
3687 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3688 case tok::lessequal: Opc = BinaryOperator::LE; break;
3689 case tok::less: Opc = BinaryOperator::LT; break;
3690 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3691 case tok::greater: Opc = BinaryOperator::GT; break;
3692 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3693 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3694 case tok::amp: Opc = BinaryOperator::And; break;
3695 case tok::caret: Opc = BinaryOperator::Xor; break;
3696 case tok::pipe: Opc = BinaryOperator::Or; break;
3697 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3698 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3699 case tok::equal: Opc = BinaryOperator::Assign; break;
3700 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3701 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3702 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3703 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3704 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3705 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3706 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3707 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3708 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3709 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3710 case tok::comma: Opc = BinaryOperator::Comma; break;
3711 }
3712 return Opc;
3713}
3714
3715static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3716 tok::TokenKind Kind) {
3717 UnaryOperator::Opcode Opc;
3718 switch (Kind) {
3719 default: assert(0 && "Unknown unary op!");
3720 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3721 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3722 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3723 case tok::star: Opc = UnaryOperator::Deref; break;
3724 case tok::plus: Opc = UnaryOperator::Plus; break;
3725 case tok::minus: Opc = UnaryOperator::Minus; break;
3726 case tok::tilde: Opc = UnaryOperator::Not; break;
3727 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003728 case tok::kw___real: Opc = UnaryOperator::Real; break;
3729 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3730 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3731 }
3732 return Opc;
3733}
3734
Douglas Gregord7f915e2008-11-06 23:29:22 +00003735/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3736/// operator @p Opc at location @c TokLoc. This routine only supports
3737/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003738Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3739 unsigned Op,
3740 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003741 QualType ResultTy; // Result type of the binary operator.
3742 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3743 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3744
3745 switch (Opc) {
3746 default:
3747 assert(0 && "Unknown binary expr!");
3748 case BinaryOperator::Assign:
3749 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3750 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003751 case BinaryOperator::PtrMemD:
3752 case BinaryOperator::PtrMemI:
3753 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3754 Opc == BinaryOperator::PtrMemI);
3755 break;
3756 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003757 case BinaryOperator::Div:
3758 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3759 break;
3760 case BinaryOperator::Rem:
3761 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3762 break;
3763 case BinaryOperator::Add:
3764 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3765 break;
3766 case BinaryOperator::Sub:
3767 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3768 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003769 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003770 case BinaryOperator::Shr:
3771 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3772 break;
3773 case BinaryOperator::LE:
3774 case BinaryOperator::LT:
3775 case BinaryOperator::GE:
3776 case BinaryOperator::GT:
3777 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3778 break;
3779 case BinaryOperator::EQ:
3780 case BinaryOperator::NE:
3781 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3782 break;
3783 case BinaryOperator::And:
3784 case BinaryOperator::Xor:
3785 case BinaryOperator::Or:
3786 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3787 break;
3788 case BinaryOperator::LAnd:
3789 case BinaryOperator::LOr:
3790 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3791 break;
3792 case BinaryOperator::MulAssign:
3793 case BinaryOperator::DivAssign:
3794 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3795 if (!CompTy.isNull())
3796 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3797 break;
3798 case BinaryOperator::RemAssign:
3799 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3800 if (!CompTy.isNull())
3801 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3802 break;
3803 case BinaryOperator::AddAssign:
3804 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3805 if (!CompTy.isNull())
3806 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3807 break;
3808 case BinaryOperator::SubAssign:
3809 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3810 if (!CompTy.isNull())
3811 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3812 break;
3813 case BinaryOperator::ShlAssign:
3814 case BinaryOperator::ShrAssign:
3815 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3816 if (!CompTy.isNull())
3817 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3818 break;
3819 case BinaryOperator::AndAssign:
3820 case BinaryOperator::XorAssign:
3821 case BinaryOperator::OrAssign:
3822 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3823 if (!CompTy.isNull())
3824 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3825 break;
3826 case BinaryOperator::Comma:
3827 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3828 break;
3829 }
3830 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003831 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003832 if (CompTy.isNull())
3833 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3834 else
3835 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003836 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003837}
3838
Chris Lattner4b009652007-07-25 00:24:17 +00003839// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003840Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3841 tok::TokenKind Kind,
3842 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003843 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003844 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003845
Steve Naroff87d58b42007-09-16 03:34:24 +00003846 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3847 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003848
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003849 // If either expression is type-dependent, just build the AST.
3850 // FIXME: We'll need to perform some caching of the result of name
3851 // lookup for operator+.
3852 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003853 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3854 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003855 Context.DependentTy,
3856 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003857 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003858 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3859 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003860 }
3861
Sebastian Redl95216a62009-02-07 00:15:38 +00003862 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003863 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3864 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003865 // If this is one of the assignment operators, we only perform
3866 // overload resolution if the left-hand side is a class or
3867 // enumeration type (C++ [expr.ass]p3).
3868 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3869 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3870 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3871 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003872
Douglas Gregord7f915e2008-11-06 23:29:22 +00003873 // Determine which overloaded operator we're dealing with.
3874 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003875 // Overloading .* is not possible.
3876 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003877 OO_Star, OO_Slash, OO_Percent,
3878 OO_Plus, OO_Minus,
3879 OO_LessLess, OO_GreaterGreater,
3880 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3881 OO_EqualEqual, OO_ExclaimEqual,
3882 OO_Amp,
3883 OO_Caret,
3884 OO_Pipe,
3885 OO_AmpAmp,
3886 OO_PipePipe,
3887 OO_Equal, OO_StarEqual,
3888 OO_SlashEqual, OO_PercentEqual,
3889 OO_PlusEqual, OO_MinusEqual,
3890 OO_LessLessEqual, OO_GreaterGreaterEqual,
3891 OO_AmpEqual, OO_CaretEqual,
3892 OO_PipeEqual,
3893 OO_Comma
3894 };
3895 OverloadedOperatorKind OverOp = OverOps[Opc];
3896
Mike Stump9afab102009-02-19 03:04:26 +00003897 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003898 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003899 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003900 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003901 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3902 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003903
3904 // Perform overload resolution.
3905 OverloadCandidateSet::iterator Best;
3906 switch (BestViableFunction(CandidateSet, Best)) {
3907 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003908 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003909 FunctionDecl *FnDecl = Best->Function;
3910
Douglas Gregor70d26122008-11-12 17:17:38 +00003911 if (FnDecl) {
3912 // We matched an overloaded operator. Build a call to that
3913 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003914
Douglas Gregor70d26122008-11-12 17:17:38 +00003915 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003916 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3917 if (PerformObjectArgumentInitialization(lhs, Method) ||
3918 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3919 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003920 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003921 } else {
3922 // Convert the arguments.
3923 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3924 "passing") ||
3925 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3926 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003927 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003928 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003929
Douglas Gregor70d26122008-11-12 17:17:38 +00003930 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003931 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003932 = FnDecl->getType()->getAsFunctionType()->getResultType();
3933 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003934
Douglas Gregor70d26122008-11-12 17:17:38 +00003935 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003936 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3937 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003938 UsualUnaryConversions(FnExpr);
3939
Mike Stump9afab102009-02-19 03:04:26 +00003940 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003941 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003942 } else {
3943 // We matched a built-in operator. Convert the arguments, then
3944 // break out so that we will build the appropriate built-in
3945 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003946 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3947 Best->Conversions[0], "passing") ||
3948 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3949 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003950 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003951
3952 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003953 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003954 }
3955
3956 case OR_No_Viable_Function:
3957 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003958 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003959 break;
3960
3961 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003962 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3963 << BinaryOperator::getOpcodeStr(Opc)
3964 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003965 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003966 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00003967
3968 case OR_Deleted:
3969 Diag(TokLoc, diag::err_ovl_deleted_oper)
3970 << Best->Function->isDeleted()
3971 << BinaryOperator::getOpcodeStr(Opc)
3972 << lhs->getSourceRange() << rhs->getSourceRange();
3973 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3974 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003975 }
3976
Douglas Gregor70d26122008-11-12 17:17:38 +00003977 // Either we found no viable overloaded operator or we matched a
3978 // built-in operator. In either case, fall through to trying to
3979 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003980 }
3981
Douglas Gregord7f915e2008-11-06 23:29:22 +00003982 // Build a built-in binary operation.
3983 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003984}
3985
3986// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003987Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3988 tok::TokenKind Op, ExprArg input) {
3989 // FIXME: Input is modified later, but smart pointer not reassigned.
3990 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003991 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003992
3993 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00003994 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003995 || Input->getType()->isEnumeralType())) {
3996 // Determine which overloaded operator we're dealing with.
3997 static const OverloadedOperatorKind OverOps[] = {
3998 OO_None, OO_None,
3999 OO_PlusPlus, OO_MinusMinus,
4000 OO_Amp, OO_Star,
4001 OO_Plus, OO_Minus,
4002 OO_Tilde, OO_Exclaim,
4003 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004004 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004005 OO_None
4006 };
4007 OverloadedOperatorKind OverOp = OverOps[Opc];
4008
Mike Stump9afab102009-02-19 03:04:26 +00004009 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004010 // to the candidate set.
4011 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004012 if (OverOp != OO_None &&
4013 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4014 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004015
4016 // Perform overload resolution.
4017 OverloadCandidateSet::iterator Best;
4018 switch (BestViableFunction(CandidateSet, Best)) {
4019 case OR_Success: {
4020 // We found a built-in operator or an overloaded operator.
4021 FunctionDecl *FnDecl = Best->Function;
4022
4023 if (FnDecl) {
4024 // We matched an overloaded operator. Build a call to that
4025 // operator.
4026
4027 // Convert the arguments.
4028 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4029 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004030 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004031 } else {
4032 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004033 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004034 FnDecl->getParamDecl(0)->getType(),
4035 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004036 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004037 }
4038
4039 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004040 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004041 = FnDecl->getType()->getAsFunctionType()->getResultType();
4042 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004043
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004044 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004045 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004046 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004047 UsualUnaryConversions(FnExpr);
4048
Sebastian Redl8b769972009-01-19 00:08:26 +00004049 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004050 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4051 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004052 } else {
4053 // We matched a built-in operator. Convert the arguments, then
4054 // break out so that we will build the appropriate built-in
4055 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004056 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4057 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004058 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004059
4060 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004061 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004062 }
4063
4064 case OR_No_Viable_Function:
4065 // No viable function; fall through to handling this as a
4066 // built-in operator, which will produce an error message for us.
4067 break;
4068
4069 case OR_Ambiguous:
4070 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4071 << UnaryOperator::getOpcodeStr(Opc)
4072 << Input->getSourceRange();
4073 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004074 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004075
4076 case OR_Deleted:
4077 Diag(OpLoc, diag::err_ovl_deleted_oper)
4078 << Best->Function->isDeleted()
4079 << UnaryOperator::getOpcodeStr(Opc)
4080 << Input->getSourceRange();
4081 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4082 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004083 }
4084
4085 // Either we found no viable overloaded operator or we matched a
4086 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004087 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004088 }
4089
Chris Lattner4b009652007-07-25 00:24:17 +00004090 QualType resultType;
4091 switch (Opc) {
4092 default:
4093 assert(0 && "Unimplemented unary expr!");
4094 case UnaryOperator::PreInc:
4095 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004096 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4097 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004098 break;
Mike Stump9afab102009-02-19 03:04:26 +00004099 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004100 resultType = CheckAddressOfOperand(Input, OpLoc);
4101 break;
Mike Stump9afab102009-02-19 03:04:26 +00004102 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004103 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004104 resultType = CheckIndirectionOperand(Input, OpLoc);
4105 break;
4106 case UnaryOperator::Plus:
4107 case UnaryOperator::Minus:
4108 UsualUnaryConversions(Input);
4109 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004110 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4111 break;
4112 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4113 resultType->isEnumeralType())
4114 break;
4115 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4116 Opc == UnaryOperator::Plus &&
4117 resultType->isPointerType())
4118 break;
4119
Sebastian Redl8b769972009-01-19 00:08:26 +00004120 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4121 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004122 case UnaryOperator::Not: // bitwise complement
4123 UsualUnaryConversions(Input);
4124 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004125 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4126 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4127 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004128 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004129 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004130 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004131 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4132 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004133 break;
4134 case UnaryOperator::LNot: // logical negation
4135 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4136 DefaultFunctionArrayConversion(Input);
4137 resultType = Input->getType();
4138 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004139 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4140 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004141 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004142 // In C++, it's bool. C++ 5.3.1p8
4143 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004144 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004145 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004146 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004147 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004148 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004149 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004150 resultType = Input->getType();
4151 break;
4152 }
4153 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004154 return ExprError();
4155 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004156 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004157}
4158
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004159/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004160Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004161 SourceLocation LabLoc,
4162 IdentifierInfo *LabelII) {
4163 // Look up the record for this label identifier.
4164 LabelStmt *&LabelDecl = LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004165
Daniel Dunbar879788d2008-08-04 16:51:22 +00004166 // If we haven't seen this label yet, create a forward reference. It
4167 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004168 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004169 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004170
Chris Lattner4b009652007-07-25 00:24:17 +00004171 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004172 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4173 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004174}
4175
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004176Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004177 SourceLocation RPLoc) { // "({..})"
4178 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4179 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4180 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4181
Eli Friedmanbc941e12009-01-24 23:09:00 +00004182 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4183 if (isFileScope) {
4184 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4185 }
4186
Chris Lattner4b009652007-07-25 00:24:17 +00004187 // FIXME: there are a variety of strange constraints to enforce here, for
4188 // example, it is not possible to goto into a stmt expression apparently.
4189 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004190
Chris Lattner4b009652007-07-25 00:24:17 +00004191 // FIXME: the last statement in the compount stmt has its value used. We
4192 // should not warn about it being unused.
4193
4194 // If there are sub stmts in the compound stmt, take the type of the last one
4195 // as the type of the stmtexpr.
4196 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004197
Chris Lattner200964f2008-07-26 19:51:01 +00004198 if (!Compound->body_empty()) {
4199 Stmt *LastStmt = Compound->body_back();
4200 // If LastStmt is a label, skip down through into the body.
4201 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4202 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004203
Chris Lattner200964f2008-07-26 19:51:01 +00004204 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004205 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004206 }
Mike Stump9afab102009-02-19 03:04:26 +00004207
Steve Naroff774e4152009-01-21 00:14:39 +00004208 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004209}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004210
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004211Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4212 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004213 SourceLocation TypeLoc,
4214 TypeTy *argty,
4215 OffsetOfComponent *CompPtr,
4216 unsigned NumComponents,
4217 SourceLocation RPLoc) {
4218 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4219 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004220
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004221 // We must have at least one component that refers to the type, and the first
4222 // one is known to be a field designator. Verify that the ArgTy represents
4223 // a struct/union/class.
4224 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004225 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004226
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004227 // Otherwise, create a compound literal expression as the base, and
4228 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004229 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004230 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004231 IList->setType(ArgTy);
4232 Expr *Res =
4233 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4234
Chris Lattnerb37522e2007-08-31 21:49:13 +00004235 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4236 // GCC extension, diagnose them.
4237 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004238 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4239 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004240
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004241 for (unsigned i = 0; i != NumComponents; ++i) {
4242 const OffsetOfComponent &OC = CompPtr[i];
4243 if (OC.isBrackets) {
4244 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004245 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004246 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004247 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004248 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004249 }
Mike Stump9afab102009-02-19 03:04:26 +00004250
Chris Lattner2af6a802007-08-30 17:59:59 +00004251 // FIXME: C++: Verify that operator[] isn't overloaded.
4252
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004253 // C99 6.5.2.1p1
4254 Expr *Idx = static_cast<Expr*>(OC.U.E);
4255 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004256 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4257 << Idx->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004258
4259 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004260 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004261 continue;
4262 }
Mike Stump9afab102009-02-19 03:04:26 +00004263
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004264 const RecordType *RC = Res->getType()->getAsRecordType();
4265 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004266 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004267 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004268 }
Mike Stump9afab102009-02-19 03:04:26 +00004269
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004270 // Get the decl corresponding to this.
4271 RecordDecl *RD = RC->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00004272 FieldDecl *MemberDecl
4273 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004274 LookupMemberName)
4275 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004276 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004277 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4278 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004279
Chris Lattner2af6a802007-08-30 17:59:59 +00004280 // FIXME: C++: Verify that MemberDecl isn't a static field.
4281 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004282 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4283 // matter here.
Mike Stump9afab102009-02-19 03:04:26 +00004284 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004285 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004286 }
Mike Stump9afab102009-02-19 03:04:26 +00004287
4288 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004289 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004290}
4291
4292
Mike Stump9afab102009-02-19 03:04:26 +00004293Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004294 TypeTy *arg1, TypeTy *arg2,
4295 SourceLocation RPLoc) {
4296 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4297 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004298
Steve Naroff63bad2d2007-08-01 22:05:33 +00004299 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004300
4301 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004302 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004303}
4304
Mike Stump9afab102009-02-19 03:04:26 +00004305Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004306 ExprTy *expr1, ExprTy *expr2,
4307 SourceLocation RPLoc) {
4308 Expr *CondExpr = static_cast<Expr*>(cond);
4309 Expr *LHSExpr = static_cast<Expr*>(expr1);
4310 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004311
Steve Naroff93c53012007-08-03 21:21:27 +00004312 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4313
4314 // The conditional expression is required to be a constant expression.
4315 llvm::APSInt condEval(32);
4316 SourceLocation ExpLoc;
4317 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004318 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4319 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004320
4321 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Mike Stump9afab102009-02-19 03:04:26 +00004322 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
Steve Naroff93c53012007-08-03 21:21:27 +00004323 RHSExpr->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004324 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004325 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004326}
4327
Steve Naroff52a81c02008-09-03 18:15:37 +00004328//===----------------------------------------------------------------------===//
4329// Clang Extensions.
4330//===----------------------------------------------------------------------===//
4331
4332/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004333void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004334 // Analyze block parameters.
4335 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004336
Steve Naroff52a81c02008-09-03 18:15:37 +00004337 // Add BSI to CurBlock.
4338 BSI->PrevBlockInfo = CurBlock;
4339 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004340
Steve Naroff52a81c02008-09-03 18:15:37 +00004341 BSI->ReturnType = 0;
4342 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004343 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004344
Steve Naroff52059382008-10-10 01:28:17 +00004345 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004346 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004347}
4348
Mike Stumpc1fddff2009-02-04 22:31:32 +00004349void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4350 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4351
4352 if (ParamInfo.getNumTypeObjects() == 0
4353 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4354 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4355
4356 // The type is entirely optional as well, if none, use DependentTy.
4357 if (T.isNull())
4358 T = Context.DependentTy;
4359
4360 // The parameter list is optional, if there was none, assume ().
4361 if (!T->isFunctionType())
4362 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4363
4364 CurBlock->hasPrototype = true;
4365 CurBlock->isVariadic = false;
4366 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4367 .getTypePtr();
4368
4369 if (!RetTy->isDependentType())
4370 CurBlock->ReturnType = RetTy;
4371 return;
4372 }
4373
Steve Naroff52a81c02008-09-03 18:15:37 +00004374 // Analyze arguments to block.
4375 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4376 "Not a function declarator!");
4377 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004378
Steve Naroff52059382008-10-10 01:28:17 +00004379 CurBlock->hasPrototype = FTI.hasPrototype;
4380 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004381
Steve Naroff52a81c02008-09-03 18:15:37 +00004382 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4383 // no arguments, not a function that takes a single void argument.
4384 if (FTI.hasPrototype &&
4385 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4386 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4387 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4388 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004389 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004390 } else if (FTI.hasPrototype) {
4391 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004392 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4393 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004394 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4395
4396 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4397 .getTypePtr();
4398
4399 if (!RetTy->isDependentType())
4400 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004401 }
Steve Naroff52059382008-10-10 01:28:17 +00004402 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004403
Steve Naroff52059382008-10-10 01:28:17 +00004404 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4405 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4406 // If this has an identifier, add it to the scope stack.
4407 if ((*AI)->getIdentifier())
4408 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004409}
4410
4411/// ActOnBlockError - If there is an error parsing a block, this callback
4412/// is invoked to pop the information about the block from the action impl.
4413void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4414 // Ensure that CurBlock is deleted.
4415 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004416
Steve Naroff52a81c02008-09-03 18:15:37 +00004417 // Pop off CurBlock, handle nested blocks.
4418 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004419
Steve Naroff52a81c02008-09-03 18:15:37 +00004420 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004421
Steve Naroff52a81c02008-09-03 18:15:37 +00004422}
4423
4424/// ActOnBlockStmtExpr - This is called when the body of a block statement
4425/// literal was successfully completed. ^(int x){...}
4426Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4427 Scope *CurScope) {
4428 // Ensure that CurBlock is deleted.
4429 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004430 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004431
Steve Naroff52059382008-10-10 01:28:17 +00004432 PopDeclContext();
4433
Steve Naroff52a81c02008-09-03 18:15:37 +00004434 // Pop off CurBlock, handle nested blocks.
4435 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004436
Steve Naroff52a81c02008-09-03 18:15:37 +00004437 QualType RetTy = Context.VoidTy;
4438 if (BSI->ReturnType)
4439 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004440
Steve Naroff52a81c02008-09-03 18:15:37 +00004441 llvm::SmallVector<QualType, 8> ArgTypes;
4442 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4443 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004444
Steve Naroff52a81c02008-09-03 18:15:37 +00004445 QualType BlockTy;
4446 if (!BSI->hasPrototype)
4447 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4448 else
4449 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004450 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004451
Steve Naroff52a81c02008-09-03 18:15:37 +00004452 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004453
Steve Naroff95029d92008-10-08 18:44:00 +00004454 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004455 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004456}
4457
Anders Carlsson36760332007-10-15 20:28:48 +00004458Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4459 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004460 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004461 Expr *E = static_cast<Expr*>(expr);
4462 QualType T = QualType::getFromOpaquePtr(type);
4463
4464 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004465
4466 // Get the va_list type
4467 QualType VaListType = Context.getBuiltinVaListType();
4468 // Deal with implicit array decay; for example, on x86-64,
4469 // va_list is an array, but it's supposed to decay to
4470 // a pointer for va_arg.
4471 if (VaListType->isArrayType())
4472 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004473 // Make sure the input expression also decays appropriately.
4474 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004475
4476 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004477 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004478 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004479 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004480
Anders Carlsson36760332007-10-15 20:28:48 +00004481 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004482
Steve Naroff774e4152009-01-21 00:14:39 +00004483 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004484}
4485
Douglas Gregorad4b3792008-11-29 04:51:27 +00004486Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4487 // The type of __null will be int or long, depending on the size of
4488 // pointers on the target.
4489 QualType Ty;
4490 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4491 Ty = Context.IntTy;
4492 else
4493 Ty = Context.LongTy;
4494
Steve Naroff774e4152009-01-21 00:14:39 +00004495 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004496}
4497
Chris Lattner005ed752008-01-04 18:04:52 +00004498bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4499 SourceLocation Loc,
4500 QualType DstType, QualType SrcType,
4501 Expr *SrcExpr, const char *Flavor) {
4502 // Decode the result (notice that AST's are still created for extensions).
4503 bool isInvalid = false;
4504 unsigned DiagKind;
4505 switch (ConvTy) {
4506 default: assert(0 && "Unknown conversion type");
4507 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004508 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004509 DiagKind = diag::ext_typecheck_convert_pointer_int;
4510 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004511 case IntToPointer:
4512 DiagKind = diag::ext_typecheck_convert_int_pointer;
4513 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004514 case IncompatiblePointer:
4515 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4516 break;
4517 case FunctionVoidPointer:
4518 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4519 break;
4520 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004521 // If the qualifiers lost were because we were applying the
4522 // (deprecated) C++ conversion from a string literal to a char*
4523 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4524 // Ideally, this check would be performed in
4525 // CheckPointerTypesForAssignment. However, that would require a
4526 // bit of refactoring (so that the second argument is an
4527 // expression, rather than a type), which should be done as part
4528 // of a larger effort to fix CheckPointerTypesForAssignment for
4529 // C++ semantics.
4530 if (getLangOptions().CPlusPlus &&
4531 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4532 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004533 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4534 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004535 case IntToBlockPointer:
4536 DiagKind = diag::err_int_to_block_pointer;
4537 break;
4538 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004539 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004540 break;
Steve Naroff19608432008-10-14 22:18:38 +00004541 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004542 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004543 // it can give a more specific diagnostic.
4544 DiagKind = diag::warn_incompatible_qualified_id;
4545 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004546 case IncompatibleVectors:
4547 DiagKind = diag::warn_incompatible_vectors;
4548 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004549 case Incompatible:
4550 DiagKind = diag::err_typecheck_convert_incompatible;
4551 isInvalid = true;
4552 break;
4553 }
Mike Stump9afab102009-02-19 03:04:26 +00004554
Chris Lattner271d4c22008-11-24 05:29:24 +00004555 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4556 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004557 return isInvalid;
4558}
Anders Carlssond5201b92008-11-30 19:50:32 +00004559
4560bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4561{
4562 Expr::EvalResult EvalResult;
4563
Mike Stump9afab102009-02-19 03:04:26 +00004564 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004565 EvalResult.HasSideEffects) {
4566 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4567
4568 if (EvalResult.Diag) {
4569 // We only show the note if it's not the usual "invalid subexpression"
4570 // or if it's actually in a subexpression.
4571 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4572 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4573 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4574 }
Mike Stump9afab102009-02-19 03:04:26 +00004575
Anders Carlssond5201b92008-11-30 19:50:32 +00004576 return true;
4577 }
4578
4579 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004580 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004581 E->getSourceRange();
4582
4583 // Print the reason it's not a constant.
4584 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4585 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4586 }
Mike Stump9afab102009-02-19 03:04:26 +00004587
Anders Carlssond5201b92008-11-30 19:50:32 +00004588 if (Result)
4589 *Result = EvalResult.Val.getInt();
4590 return false;
4591}